diff --git a/submodules/AppLock/Sources/AppLock.swift b/submodules/AppLock/Sources/AppLock.swift index 51e480825e..ccaceca2ac 100644 --- a/submodules/AppLock/Sources/AppLock.swift +++ b/submodules/AppLock/Sources/AppLock.swift @@ -120,7 +120,7 @@ public final class AppLockContextImpl: AppLockContext { return } - let passcodeSettings: PresentationPasscodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings] as? PresentationPasscodeSettings ?? .defaultSettings + let passcodeSettings: PresentationPasscodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]?.get(PresentationPasscodeSettings.self) ?? .defaultSettings let timestamp = CFAbsoluteTimeGetCurrent() var becameActiveRecently = false diff --git a/submodules/CallListUI/Sources/CallListControllerNode.swift b/submodules/CallListUI/Sources/CallListControllerNode.swift index bd995283c0..fee8c3a6bc 100644 --- a/submodules/CallListUI/Sources/CallListControllerNode.swift +++ b/submodules/CallListUI/Sources/CallListControllerNode.swift @@ -453,7 +453,7 @@ final class CallListControllerNode: ASDisplayNode { let showCallsTab = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.callListSettings]) |> map { sharedData -> Bool in var value = CallListSettings.defaultSettings.showTab - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings] as? CallListSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings]?.get(CallListSettings.self) { value = settings.showTab } return value diff --git a/submodules/ChatListUI/Sources/ChatContextMenus.swift b/submodules/ChatListUI/Sources/ChatContextMenus.swift index 52f12478f7..6c44f427ad 100644 --- a/submodules/ChatListUI/Sources/ChatContextMenus.swift +++ b/submodules/ChatListUI/Sources/ChatContextMenus.swift @@ -29,7 +29,7 @@ func archiveContextMenuItems(context: AccountContext, groupId: PeerGroupId, chat }))) } - let settings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.chatArchiveSettings) as? ChatArchiveSettings ?? ChatArchiveSettings.default + let settings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.chatArchiveSettings)?.get(ChatArchiveSettings.self) ?? ChatArchiveSettings.default let isPinned = !settings.isHiddenByDefault items.append(.action(ContextMenuActionItem(text: isPinned ? strings.ChatList_Context_HideArchive : strings.ChatList_Context_UnhideArchive, icon: { theme in generateTintedImage(image: UIImage(bundleImageName: isPinned ? "Chat/Context Menu/Unpin": "Chat/Context Menu/Pin"), color: theme.contextMenu.primaryColor) }, action: { [weak chatListController] _, f in chatListController?.toggleArchivedFolderHiddenByDefault() diff --git a/submodules/ChatListUI/Sources/ChatListController.swift b/submodules/ChatListUI/Sources/ChatListController.swift index 5e20fd528e..304eef16ea 100644 --- a/submodules/ChatListUI/Sources/ChatListController.swift +++ b/submodules/ChatListUI/Sources/ChatListController.swift @@ -262,7 +262,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController let hasProxy = context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> map { sharedData -> (Bool, Bool) in - if let settings = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let settings = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { return (!settings.servers.isEmpty, settings.enabled) } else { return (false, false) @@ -1192,7 +1192,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController let context = self.context let signal = combineLatest(self.context.sharedContext.accountManager.transaction { transaction -> String in let languageCode: String - if let current = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings { + if let current = transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self) { let code = current.primaryComponent.languageCode let rawSuffix = "-raw" if code.hasSuffix(rawSuffix) { @@ -1206,7 +1206,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController return languageCode }, self.context.account.postbox.transaction { transaction -> SuggestedLocalizationEntry? in var suggestedLocalization: SuggestedLocalizationEntry? - if let localization = transaction.getPreferencesEntry(key: PreferencesKeys.suggestedLocalization) as? SuggestedLocalizationEntry { + if let localization = transaction.getPreferencesEntry(key: PreferencesKeys.suggestedLocalization)?.get(SuggestedLocalizationEntry.self) { suggestedLocalization = localization } return suggestedLocalization @@ -1291,7 +1291,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController PreferencesKeys.chatListFiltersFeaturedState ]) |> mapToSignal { view -> Signal in - if let entry = view.values[PreferencesKeys.chatListFiltersFeaturedState] as? ChatListFiltersFeaturedState { + if let entry = view.values[PreferencesKeys.chatListFiltersFeaturedState]?.get(ChatListFiltersFeaturedState.self) { return .single(!entry.filters.isEmpty && !entry.isSeen) } else { return .complete() @@ -1537,7 +1537,7 @@ public class ChatListControllerImpl: TelegramBaseController, ChatListController let experimentalUISettingsKey: ValueBoxKey = ApplicationSpecificSharedDataKeys.experimentalUISettings let displayTabsAtBottom = self.context.sharedContext.accountManager.sharedData(keys: Set([experimentalUISettingsKey])) |> map { sharedData -> Bool in - let settings: ExperimentalUISettings = sharedData.entries[experimentalUISettingsKey] as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + let settings: ExperimentalUISettings = sharedData.entries[experimentalUISettingsKey]?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings return settings.foldersTabAtBottom } |> distinctUntilChanged diff --git a/submodules/ChatListUI/Sources/ChatListFilterPresetListController.swift b/submodules/ChatListUI/Sources/ChatListFilterPresetListController.swift index e9a86e85ff..0d4529588c 100644 --- a/submodules/ChatListUI/Sources/ChatListFilterPresetListController.swift +++ b/submodules/ChatListUI/Sources/ChatListFilterPresetListController.swift @@ -307,7 +307,7 @@ public func chatListFilterPresetListController(context: AccountContext, mode: Ch let featuredFilters = context.account.postbox.preferencesView(keys: [PreferencesKeys.chatListFiltersFeaturedState]) |> map { preferences -> [ChatListFeaturedFilter] in - guard let state = preferences.values[PreferencesKeys.chatListFiltersFeaturedState] as? ChatListFiltersFeaturedState else { + guard let state = preferences.values[PreferencesKeys.chatListFiltersFeaturedState]?.get(ChatListFiltersFeaturedState.self) else { return [] } return state.filters @@ -330,7 +330,7 @@ public func chatListFilterPresetListController(context: AccountContext, mode: Ch featuredFilters ) |> map { presentationData, state, filtersWithCountsValue, preferences, updatedFilterOrderValue, suggestedFilters -> (ItemListControllerState, (ItemListNodeState, Any)) in - let filterSettings = preferences.values[ApplicationSpecificPreferencesKeys.chatListFilterSettings] as? ChatListFilterSettings ?? ChatListFilterSettings.default + let filterSettings = preferences.values[ApplicationSpecificPreferencesKeys.chatListFilterSettings]?.get(ChatListFilterSettings.self) ?? ChatListFilterSettings.default let leftNavigationButton: ItemListNavigationButton? switch mode { case .default: diff --git a/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift b/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift index 30b18e6ca3..9e17ca6471 100644 --- a/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift +++ b/submodules/ChatListUI/Sources/ChatListSearchListPaneNode.swift @@ -1743,10 +1743,10 @@ final class ChatListSearchListPaneNode: ASDisplayNode, ChatListSearchPaneNode { return } let _ = (strongSelf.context.sharedContext.accountManager.transaction { transaction -> AudioPlaybackRate in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings) as? MusicPlaybackSettings ?? MusicPlaybackSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings)?.get(MusicPlaybackSettings.self) ?? MusicPlaybackSettings.defaultSettings transaction.updateSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings, { _ in - return settings.withUpdatedVoicePlaybackRate(rate) + return PreferencesEntry(settings.withUpdatedVoicePlaybackRate(rate)) }) return rate } diff --git a/submodules/ChatListUI/Sources/Node/ChatListNode.swift b/submodules/ChatListUI/Sources/Node/ChatListNode.swift index 7bae52d5e5..0a8889f411 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListNode.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListNode.swift @@ -806,7 +806,7 @@ public final class ChatListNode: ListView { let hideArchivedFolderByDefault = context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.chatArchiveSettings]) |> map { view -> Bool in - let settings: ChatArchiveSettings = view.values[ApplicationSpecificPreferencesKeys.chatArchiveSettings] as? ChatArchiveSettings ?? .default + let settings: ChatArchiveSettings = view.values[ApplicationSpecificPreferencesKeys.chatArchiveSettings]?.get(ChatArchiveSettings.self) ?? .default return settings.isHiddenByDefault } |> distinctUntilChanged @@ -1759,7 +1759,7 @@ public final class ChatListNode: ListView { let postbox = self.context.account.postbox return self.context.sharedContext.accountManager.transaction { transaction -> Signal in var filter = true - if let inAppNotificationSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings) as? InAppNotificationSettings { + if let inAppNotificationSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings)?.get(InAppNotificationSettings.self) { switch inAppNotificationSettings.totalUnreadCountDisplayStyle { case .filtered: filter = true diff --git a/submodules/ContactListUI/Sources/ContactListNode.swift b/submodules/ContactListUI/Sources/ContactListNode.swift index 63b019afa2..8763324c68 100644 --- a/submodules/ContactListUI/Sources/ContactListNode.swift +++ b/submodules/ContactListUI/Sources/ContactListNode.swift @@ -904,7 +904,7 @@ public final class ContactListNode: ASDisplayNode { |> then( combineLatest(context.sharedContext.accountManager.noticeEntry(key: ApplicationSpecificNotice.permissionWarningKey(permission: .contacts)!), context.account.postbox.preferencesView(keys: [PreferencesKeys.contactsSettings])) |> map { noticeView, preferences -> (Bool, Bool) in - let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings] as? ContactsSettings ?? ContactsSettings.defaultSettings + let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings]?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings let synchronizeDeviceContacts: Bool = settings.synchronizeContacts let suppressed: Bool let timestamp = noticeView.value.flatMap({ ApplicationSpecificNotice.getTimestampValue($0) }) diff --git a/submodules/ContactListUI/Sources/ContactsController.swift b/submodules/ContactListUI/Sources/ContactsController.swift index 7b83ff45d2..3b94c6845e 100644 --- a/submodules/ContactListUI/Sources/ContactsController.swift +++ b/submodules/ContactListUI/Sources/ContactsController.swift @@ -146,10 +146,10 @@ public class ContactsController: ViewController { if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { self.authorizationDisposable = (combineLatest(DeviceAccess.authorizationStatus(subject: .contacts), combineLatest(context.sharedContext.accountManager.noticeEntry(key: ApplicationSpecificNotice.permissionWarningKey(permission: .contacts)!), context.account.postbox.preferencesView(keys: [PreferencesKeys.contactsSettings]), context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.contactSynchronizationSettings])) |> map { noticeView, preferences, sharedData -> (Bool, ContactsSortOrder) in - let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings] as? ContactsSettings ?? ContactsSettings.defaultSettings + let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings]?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings let synchronizeDeviceContacts: Bool = settings.synchronizeContacts - let contactsSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings + let contactsSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]?.get(ContactSynchronizationSettings.self) let sortOrder: ContactsSortOrder = contactsSettings?.sortOrder ?? .presence if !synchronizeDeviceContacts { @@ -172,7 +172,7 @@ public class ContactsController: ViewController { } else { self.sortOrderPromise.set(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]) |> map { sharedData -> ContactsSortOrder in - let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]?.get(ContactSynchronizationSettings.self) return settings?.sortOrder ?? .presence }) } diff --git a/submodules/DebugSettingsUI/Sources/DebugController.swift b/submodules/DebugSettingsUI/Sources/DebugController.swift index 10f86849f8..af88301644 100644 --- a/submodules/DebugSettingsUI/Sources/DebugController.swift +++ b/submodules/DebugSettingsUI/Sources/DebugController.swift @@ -76,7 +76,6 @@ private enum DebugControllerEntry: ItemListNodeEntry { case optimizeDatabase(PresentationTheme) case photoPreview(PresentationTheme, Bool) case knockoutWallpaper(PresentationTheme, Bool) - case demoVideoChats(Bool) case experimentalCompatibility(Bool) case enableDebugDataDisplay(Bool) case playerEmbedding(Bool) @@ -100,7 +99,7 @@ private enum DebugControllerEntry: ItemListNodeEntry { return DebugControllerSection.logging.rawValue case .enableRaiseToSpeak, .keepChatNavigationStack, .skipReadHistory, .crashOnSlowQueries: return DebugControllerSection.experiments.rawValue - case .clearTips, .crash, .resetData, .resetDatabase, .resetDatabaseAndCache, .resetHoles, .reindexUnread, .resetBiometricsData, .optimizeDatabase, .photoPreview, .knockoutWallpaper, .demoVideoChats, .playerEmbedding, .playlistPlayback, .voiceConference, .experimentalCompatibility, .enableDebugDataDisplay: + case .clearTips, .crash, .resetData, .resetDatabase, .resetDatabaseAndCache, .resetHoles, .reindexUnread, .resetBiometricsData, .optimizeDatabase, .photoPreview, .knockoutWallpaper, .playerEmbedding, .playlistPlayback, .voiceConference, .experimentalCompatibility, .enableDebugDataDisplay: return DebugControllerSection.experiments.rawValue case .preferredVideoCodec: return DebugControllerSection.videoExperiments.rawValue @@ -163,8 +162,6 @@ private enum DebugControllerEntry: ItemListNodeEntry { return 23 case .knockoutWallpaper: return 24 - case .demoVideoChats: - return 25 case .experimentalCompatibility: return 26 case .enableDebugDataDisplay: @@ -703,9 +700,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Media Preview (Updated)", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.chatListPhotos = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -713,19 +710,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Knockout Wallpaper", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.knockoutWallpaper = value - return settings - }) - }).start() - }) - case let .demoVideoChats(value): - return ItemListSwitchItem(presentationData: presentationData, title: "Demo Video", value: value, sectionId: self.section, style: .blocks, updated: { value in - let _ = arguments.sharedContext.accountManager.transaction ({ transaction in - transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings - settings.demoVideoChats = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -733,9 +720,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Experimental Compatibility", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.experimentalCompatibility = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -743,9 +730,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Debug Data Display", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.enableDebugDataDisplay = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -753,9 +740,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Player Embedding", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.playerEmbedding = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -763,9 +750,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Playlist Playback", value: value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.playlistPlayback = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -779,9 +766,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListCheckboxItem(presentationData: presentationData, title: title, style: .right, checked: isSelected, zeroSeparatorInsets: false, sectionId: self.section, action: { let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.preferredVideoCodec = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -789,9 +776,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Video Cropping Optimization", value: !value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.disableVideoAspectScaling = !value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -799,9 +786,9 @@ private enum DebugControllerEntry: ItemListNodeEntry { return ItemListSwitchItem(presentationData: presentationData, title: "Enable VoIP TCP", value: !value, sectionId: self.section, style: .blocks, updated: { value in let _ = arguments.sharedContext.accountManager.transaction ({ transaction in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { settings in - var settings = settings as? ExperimentalUISettings ?? ExperimentalUISettings.defaultSettings + var settings = settings?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings settings.enableVoipTcp = value - return settings + return PreferencesEntry(settings) }) }).start() }) @@ -858,7 +845,6 @@ private func debugControllerEntries(sharedContext: SharedAccountContext, present entries.append(.optimizeDatabase(presentationData.theme)) if isMainApp { entries.append(.knockoutWallpaper(presentationData.theme, experimentalSettings.knockoutWallpaper)) - entries.append(.demoVideoChats(experimentalSettings.demoVideoChats)) entries.append(.experimentalCompatibility(experimentalSettings.experimentalCompatibility)) entries.append(.enableDebugDataDisplay(experimentalSettings.enableDebugDataDisplay)) entries.append(.playerEmbedding(experimentalSettings.playerEmbedding)) @@ -927,22 +913,22 @@ public func debugController(sharedContext: SharedAccountContext, context: Accoun let signal = combineLatest(sharedContext.presentationData, sharedContext.accountManager.sharedData(keys: Set([SharedDataKeys.loggingSettings, ApplicationSpecificSharedDataKeys.mediaInputSettings, ApplicationSpecificSharedDataKeys.experimentalUISettings])), preferencesSignal) |> map { presentationData, sharedData, preferences -> (ItemListControllerState, (ItemListNodeState, Any)) in let loggingSettings: LoggingSettings - if let value = sharedData.entries[SharedDataKeys.loggingSettings] as? LoggingSettings { + if let value = sharedData.entries[SharedDataKeys.loggingSettings]?.get(LoggingSettings.self) { loggingSettings = value } else { loggingSettings = LoggingSettings.defaultSettings } let mediaInputSettings: MediaInputSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.mediaInputSettings] as? MediaInputSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.mediaInputSettings]?.get(MediaInputSettings.self) { mediaInputSettings = value } else { mediaInputSettings = MediaInputSettings.defaultSettings } - let experimentalSettings: ExperimentalUISettings = (sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings] as? ExperimentalUISettings) ?? ExperimentalUISettings.defaultSettings + let experimentalSettings: ExperimentalUISettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings]?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings - let networkSettings: NetworkSettings? = preferences?.values[PreferencesKeys.networkSettings] as? NetworkSettings + let networkSettings: NetworkSettings? = preferences?.values[PreferencesKeys.networkSettings]?.get(NetworkSettings.self) var leftNavigationButton: ItemListNavigationButton? if modal { diff --git a/submodules/GalleryUI/Sources/GalleryController.swift b/submodules/GalleryUI/Sources/GalleryController.swift index df117ca2e1..6042c2c2e6 100644 --- a/submodules/GalleryUI/Sources/GalleryController.swift +++ b/submodules/GalleryUI/Sources/GalleryController.swift @@ -488,7 +488,7 @@ public class GalleryController: ViewController, StandalonePresentableController let f: () -> Void = { if let strongSelf = self { if let view = view { - let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue let configuration = GalleryConfiguration.with(appConfiguration: appConfiguration) strongSelf.configuration = configuration diff --git a/submodules/InstantPageUI/Sources/InstantPageController.swift b/submodules/InstantPageUI/Sources/InstantPageController.swift index 776dcfb509..c5a2bb408f 100644 --- a/submodules/InstantPageUI/Sources/InstantPageController.swift +++ b/submodules/InstantPageUI/Sources/InstantPageController.swift @@ -109,13 +109,13 @@ public final class InstantPageController: ViewController { |> deliverOnMainQueue).start(next: { [weak self] sharedData in if let strongSelf = self { let settings: InstantPagePresentationSettings - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.instantPagePresentationSettings] as? InstantPagePresentationSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.instantPagePresentationSettings]?.get(InstantPagePresentationSettings.self) { settings = current } else { settings = InstantPagePresentationSettings.defaultSettings } let themeSettings: PresentationThemeSettings - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) { themeSettings = current } else { themeSettings = PresentationThemeSettings.defaultSettings diff --git a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h index 3a06e3c3bf..f60b4f83d8 100644 --- a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h +++ b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.h @@ -23,6 +23,8 @@ typedef enum { - (bool)checkObjectIsKindOfClass:(Class _Nonnull)targetClass; - (void)setClass:(Class _Nonnull)newClass; +- (NSNumber * _Nullable)floatValueForKeyPath:(NSString * _Nonnull)keyPath; + @end SEL _Nonnull makeSelectorFromString(NSString * _Nonnull string); diff --git a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.m b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.m index 060faf64d0..742c98fb6c 100644 --- a/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.m +++ b/submodules/ObjCRuntimeUtils/Source/ObjCRuntimeUtils/RuntimeUtils.m @@ -98,27 +98,17 @@ object_setClass(self, newClass); } -static Class freedomMakeClass(Class superclass, Class subclass, SEL *copySelectors, int copySelectorsCount) -{ - if (superclass == Nil || subclass == Nil) - return nil; - - Class decoratedClass = objc_allocateClassPair(superclass, [[NSString alloc] initWithFormat:@"%@_%@", NSStringFromClass(superclass), NSStringFromClass(subclass)].UTF8String, 0); - - unsigned int count = 0; - Method *methodList = class_copyMethodList(subclass, &count); - if (methodList != NULL) { - for (unsigned int i = 0; i < count; i++) { - SEL methodName = method_getName(methodList[i]); - class_addMethod(decoratedClass, methodName, method_getImplementation(methodList[i]), method_getTypeEncoding(methodList[i])); +- (NSNumber * _Nullable)floatValueForKeyPath:(NSString * _Nonnull)keyPath { + id value = [self valueForKeyPath:keyPath]; + if (value != nil) { + if ([value respondsToSelector:@selector(floatValue)]) { + return @([value floatValue]); + } else { + return nil; } - - free(methodList); + } else { + return nil; } - - objc_registerClassPair(decoratedClass); - - return decoratedClass; } @end diff --git a/submodules/PeerInfoUI/Sources/ChannelInfoController.swift b/submodules/PeerInfoUI/Sources/ChannelInfoController.swift index cfdba3954f..917209a4f7 100644 --- a/submodules/PeerInfoUI/Sources/ChannelInfoController.swift +++ b/submodules/PeerInfoUI/Sources/ChannelInfoController.swift @@ -823,7 +823,7 @@ public func channelInfoController(context: AccountContext, peerId: PeerId) -> Vi let presentationData = context.sharedContext.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 + let globalSettings: GlobalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) } |> deliverOnMainQueue).start(next: { peerSettings, globalSettings in @@ -929,7 +929,7 @@ public func channelInfoController(context: AccountContext, peerId: PeerId) -> Vi var globalNotificationSettings: GlobalNotificationSettings = GlobalNotificationSettings.defaultSettings if let preferencesView = combinedView.views[globalNotificationsKey] as? PreferencesView { - if let settings = preferencesView.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = preferencesView.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { globalNotificationSettings = settings } } diff --git a/submodules/PeerInfoUI/Sources/GroupStickerPackSetupController.swift b/submodules/PeerInfoUI/Sources/GroupStickerPackSetupController.swift index 7dc0927e21..42ab698ded 100644 --- a/submodules/PeerInfoUI/Sources/GroupStickerPackSetupController.swift +++ b/submodules/PeerInfoUI/Sources/GroupStickerPackSetupController.swift @@ -405,7 +405,7 @@ public func groupStickerPackSetupController(context: AccountContext, peerId: Pee let signal = combineLatest(context.sharedContext.presentationData, statePromise.get() |> deliverOnMainQueue, initialData.get() |> deliverOnMainQueue, stickerPacks.get() |> deliverOnMainQueue, searchState.get() |> deliverOnMainQueue, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.stickerSettings]) |> deliverOnMainQueue) |> map { presentationData, state, initialData, view, searchState, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } diff --git a/submodules/PeersNearbyUI/Sources/PeersNearbyController.swift b/submodules/PeersNearbyUI/Sources/PeersNearbyController.swift index 13bb221089..e266e24cef 100644 --- a/submodules/PeersNearbyUI/Sources/PeersNearbyController.swift +++ b/submodules/PeersNearbyUI/Sources/PeersNearbyController.swift @@ -573,7 +573,7 @@ public func peersNearbyController(context: AccountContext) -> ViewController { |> deliverOnMainQueue |> map { presentationData, data, chatLocation, displayLoading, expanded, view -> (ItemListControllerState, (ItemListNodeState, Any)) in let previous = previousData.swap(data) - let state = view.values[PreferencesKeys.peersNearby] as? PeersNearbyState ?? .default + let state = view.values[PreferencesKeys.peersNearby]?.get(PeersNearbyState.self) ?? .default var crossfade = false if (data?.users.isEmpty ?? true) != (previous?.users.isEmpty ?? true) { diff --git a/submodules/Postbox/Sources/Coding.swift b/submodules/Postbox/Sources/Coding.swift index ed733889cd..8e1c769ddf 100644 --- a/submodules/Postbox/Sources/Coding.swift +++ b/submodules/Postbox/Sources/Coding.swift @@ -444,6 +444,15 @@ public final class PostboxEncoder { return } } + + public func encodeObjectToRawData(_ value: T) -> AdaptedPostboxEncoder.RawObjectData { + let typeHash: Int32 = murMurHashString32("\(type(of: value))") + + let innerEncoder = PostboxEncoder() + value.encode(innerEncoder) + + return AdaptedPostboxEncoder.RawObjectData(typeHash: typeHash, data: innerEncoder.makeData()) + } public func encodeObjectArray(_ value: [T], forKey key: String) { self.encodeKey(key) @@ -649,7 +658,7 @@ public final class PostboxEncoder { let innerEncoder = _AdaptedPostboxEncoder(typeHash: typeHash) try! value.encode(to: innerEncoder) - let (data, valueType) = innerEncoder.makeData(addHeader: true) + let (data, valueType) = innerEncoder.makeData(addHeader: true, isDictionary: false) self.encodeInnerObjectData(data, valueType: valueType, forKey: key) } @@ -1011,6 +1020,10 @@ public final class PostboxDecoder { public func decodeRootObject() -> PostboxCoding? { return self.decodeObjectForKey("_") } + + public func decodeRootObjectWithHash(hash: Int32) -> PostboxCoding? { + return typeStore.decode(hash, decoder: self) + } public func decodeCodable(_ type: T.Type, forKey key: String) -> T? { if let data = self.decodeDataForKey(key) { @@ -1651,6 +1664,43 @@ public final class PostboxDecoder { return [:] } } + + public func decodeObjectDataDictRaw() -> [(Data, Data)] { + var dict: [(Data, Data)] = [] + + var length: Int32 = 0 + memcpy(&length, self.buffer.memory + self.offset, 4) + self.offset += 4 + + var i: Int32 = 0 + while i < length { + var keyHash: Int32 = 0 + memcpy(&keyHash, self.buffer.memory + self.offset, 4) + self.offset += 4 + + var keyLength: Int32 = 0 + memcpy(&keyLength, self.buffer.memory + self.offset, 4) + + let keyData = ReadBuffer(memory: self.buffer.memory + (self.offset + 4), length: Int(keyLength), freeWhenDone: false).makeData() + self.offset += 4 + Int(keyLength) + + var valueHash: Int32 = 0 + memcpy(&valueHash, self.buffer.memory + self.offset, 4) + self.offset += 4 + + var valueLength: Int32 = 0 + memcpy(&valueLength, self.buffer.memory + self.offset, 4) + + let objectData = ReadBuffer(memory: self.buffer.memory + (self.offset + 4), length: Int(valueLength), freeWhenDone: false).makeData() + self.offset += 4 + Int(valueLength) + + dict.append((keyData, objectData)) + + i += 1 + } + + return dict + } public func decodeBytesForKeyNoCopy(_ key: String) -> ReadBuffer? { if PostboxDecoder.positionOnKey(self.buffer.memory, offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Bytes) { @@ -1728,7 +1778,13 @@ public final class PostboxDecoder { let innerData = innerBuffer.makeData() self.offset += 4 + Int(length) - return try? AdaptedPostboxDecoder().decode(T.self, from: innerData) + do { + let result = try AdaptedPostboxDecoder().decode(T.self, from: innerData) + return result + } catch let error { + assertionFailure("Decoding error: \(error)") + return nil + } } else { return nil } diff --git a/submodules/Postbox/Sources/PreferencesEntry.swift b/submodules/Postbox/Sources/PreferencesEntry.swift index 4d3e89714e..a38f5cae4b 100644 --- a/submodules/Postbox/Sources/PreferencesEntry.swift +++ b/submodules/Postbox/Sources/PreferencesEntry.swift @@ -1,6 +1,6 @@ import Foundation -public final class PreferencesEntry: Equatable { +public final class CodableEntry: Equatable { public let data: Data public init(data: Data) { @@ -18,6 +18,34 @@ public final class PreferencesEntry: Equatable { return decoder.decode(T.self, forKey: "_") } + public static func ==(lhs: CodableEntry, rhs: CodableEntry) -> Bool { + return lhs.data == rhs.data + } +} + +public final class PreferencesEntry: Equatable { + public let data: Data + + public init(data: Data) { + self.data = data + } + + public init?(_ value: T?) { + guard let value = value else { + return nil + } + let encoder = PostboxEncoder() + encoder.encode(value, forKey: "_") + self.data = encoder.makeData() + } + + public func get(_ type: T.Type) -> T? { + let decoder = PostboxDecoder(buffer: MemoryBuffer(data: self.data)) + let result = decoder.decode(T.self, forKey: "_") + assert(result != nil) + return result + } + public static func ==(lhs: PreferencesEntry, rhs: PreferencesEntry) -> Bool { return lhs.data == rhs.data } diff --git a/submodules/Postbox/Sources/SeedConfiguration.swift b/submodules/Postbox/Sources/SeedConfiguration.swift index e8b0a8520d..4b9fd4e475 100644 --- a/submodules/Postbox/Sources/SeedConfiguration.swift +++ b/submodules/Postbox/Sources/SeedConfiguration.swift @@ -72,7 +72,27 @@ public final class SeedConfiguration { public let getGlobalNotificationSettings: (Transaction) -> PostboxGlobalNotificationSettings? public let defaultGlobalNotificationSettings: PostboxGlobalNotificationSettings - public init(globalMessageIdsPeerIdNamespaces: Set, initializeChatListWithHole: (topLevel: ChatListHole?, groups: ChatListHole?), messageHoles: [PeerId.Namespace: [MessageId.Namespace: Set]], upgradedMessageHoles: [PeerId.Namespace: [MessageId.Namespace: Set]], messageThreadHoles: [PeerId.Namespace: [MessageId.Namespace]], existingMessageTags: MessageTags, messageTagsWithSummary: MessageTags, existingGlobalMessageTags: GlobalMessageTags, peerNamespacesRequiringMessageTextIndex: [PeerId.Namespace], peerSummaryCounterTags: @escaping (Peer, Bool) -> PeerSummaryCounterTags, additionalChatListIndexNamespace: MessageId.Namespace?, messageNamespacesRequiringGroupStatsValidation: Set, defaultMessageNamespaceReadStates: [MessageId.Namespace: PeerReadState], chatMessagesNamespaces: Set, getGlobalNotificationSettings: @escaping (Transaction) -> PostboxGlobalNotificationSettings?, defaultGlobalNotificationSettings: PostboxGlobalNotificationSettings) { + public init( + globalMessageIdsPeerIdNamespaces: Set, + initializeChatListWithHole: ( + topLevel: ChatListHole?, + groups: ChatListHole? + ), + messageHoles: [PeerId.Namespace: [MessageId.Namespace: Set]], + upgradedMessageHoles: [PeerId.Namespace: [MessageId.Namespace: Set]], + messageThreadHoles: [PeerId.Namespace: [MessageId.Namespace]], + existingMessageTags: MessageTags, + messageTagsWithSummary: MessageTags, + existingGlobalMessageTags: GlobalMessageTags, + peerNamespacesRequiringMessageTextIndex: [PeerId.Namespace], + peerSummaryCounterTags: @escaping (Peer, Bool) -> PeerSummaryCounterTags, + additionalChatListIndexNamespace: MessageId.Namespace?, + messageNamespacesRequiringGroupStatsValidation: Set, + defaultMessageNamespaceReadStates: [MessageId.Namespace: PeerReadState], + chatMessagesNamespaces: Set, + getGlobalNotificationSettings: @escaping (Transaction) -> PostboxGlobalNotificationSettings?, + defaultGlobalNotificationSettings: PostboxGlobalNotificationSettings + ) { self.globalMessageIdsPeerIdNamespaces = globalMessageIdsPeerIdNamespaces self.initializeChatListWithHole = initializeChatListWithHole self.messageHoles = messageHoles diff --git a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift index 23e6b1475d..4f25acfd9c 100644 --- a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift +++ b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift @@ -8,9 +8,10 @@ final public class AdaptedPostboxDecoder { case objectArray case stringArray case dataArray + case objectDict } - public final class RawObjectData: Codable { + public final class RawObjectData: Decodable { public let data: Data public let typeHash: Int32 @@ -55,7 +56,7 @@ extension AdaptedPostboxDecoder.ContentType { case .ObjectArray: self = .objectArray case .ObjectDictionary: - return nil + self = .objectDict case .Bytes: return nil case .Nil: @@ -117,6 +118,8 @@ extension _AdaptedPostboxDecoder: Decoder { content = .stringArray(decoder.decodeStringArrayRaw()) case .dataArray: content = .dataArray(decoder.decodeBytesArrayRaw().map { $0.makeData() }) + case .objectDict: + content = .objectDict(decoder.decodeObjectDataDictRaw()) } if let content = content { diff --git a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxUnkeyedDecodingContainer.swift b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxUnkeyedDecodingContainer.swift index 27bdeddcfd..e9a15f2705 100644 --- a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxUnkeyedDecodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxUnkeyedDecodingContainer.swift @@ -8,6 +8,7 @@ extension _AdaptedPostboxDecoder { case objectArray([Data]) case stringArray([String]) case dataArray([Data]) + case objectDict([(Data, Data)]) var count: Int { switch self { @@ -21,6 +22,8 @@ extension _AdaptedPostboxDecoder { return array.count case let .dataArray(array): return array.count + case let .objectDict(dict): + return dict.count * 2 } } } @@ -64,6 +67,7 @@ extension _AdaptedPostboxDecoder.UnkeyedContainer: UnkeyedDecodingContainer { self._currentIndex += 1 return array[index] as! T default: + assertionFailure() throw DecodingError.typeMismatch(Data.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "")) } } else { @@ -74,7 +78,35 @@ extension _AdaptedPostboxDecoder.UnkeyedContainer: UnkeyedDecodingContainer { let data = array[index] return try AdaptedPostboxDecoder().decode(T.self, from: data) + case let .objectDict(dict): + let index = self._currentIndex + self._currentIndex += 1 + + let dataPair = dict[index / 2] + let data: Data + if index % 2 == 0 { + data = dataPair.0 + } else { + data = dataPair.1 + } + return try AdaptedPostboxDecoder().decode(T.self, from: data) + case let .int32Array(array): + let index = self._currentIndex + self._currentIndex += 1 + + return array[index] as! T + case let .int64Array(array): + let index = self._currentIndex + self._currentIndex += 1 + + return array[index] as! T + case let .stringArray(array): + let index = self._currentIndex + self._currentIndex += 1 + + return array[index] as! T default: + assertionFailure() throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "")) } } diff --git a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxEncoder.swift b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxEncoder.swift index 5c46082034..3851657b9e 100644 --- a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxEncoder.swift +++ b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxEncoder.swift @@ -2,6 +2,16 @@ import Foundation import MurMurHash32 public class AdaptedPostboxEncoder { + public final class RawObjectData: Encodable { + public let typeHash: Int32 + public let data: Data + + public init(typeHash: Int32, data: Data) { + self.typeHash = typeHash + self.data = data + } + } + public init() { } @@ -10,7 +20,7 @@ public class AdaptedPostboxEncoder { let encoder = _AdaptedPostboxEncoder(typeHash: typeHash) try value.encode(to: encoder) - return encoder.makeData(addHeader: false).0 + return encoder.makeData(addHeader: false, isDictionary: false).0 } } @@ -27,8 +37,8 @@ final class _AdaptedPostboxEncoder { self.typeHash = typeHash } - func makeData(addHeader: Bool) -> (Data, ValueType) { - return self.container!.makeData(addHeader: addHeader) + func makeData(addHeader: Bool, isDictionary: Bool) -> (Data, ValueType) { + return self.container!.makeData(addHeader: addHeader, isDictionary: isDictionary) } } @@ -61,5 +71,5 @@ extension _AdaptedPostboxEncoder: Encoder { } protocol AdaptedPostboxEncodingContainer: AnyObject { - func makeData(addHeader: Bool) -> (Data, ValueType) + func makeData(addHeader: Bool, isDictionary: Bool) -> (Data, ValueType) } diff --git a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxKeyedEncodingContainer.swift b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxKeyedEncodingContainer.swift index 311d3edcf2..cd152c85e1 100644 --- a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxKeyedEncodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxKeyedEncodingContainer.swift @@ -17,7 +17,7 @@ extension _AdaptedPostboxEncoder { self.encoder = PostboxEncoder() } - func makeData(addHeader: Bool) -> (Data, ValueType) { + func makeData(addHeader: Bool, isDictionary: Bool) -> (Data, ValueType) { let buffer = WriteBuffer() if addHeader { @@ -43,12 +43,27 @@ extension _AdaptedPostboxEncoder.KeyedContainer: KeyedEncodingContainerProtocol func encode(_ value: T, forKey key: Key) throws where T : Encodable { if let value = value as? Data { self.encoder.encodeData(value, forKey: key.stringValue) + } else if let value = value as? AdaptedPostboxEncoder.RawObjectData { + let typeHash: Int32 = value.typeHash + let innerEncoder = _AdaptedPostboxEncoder(typeHash: typeHash) + try! value.encode(to: innerEncoder) + + let (data, valueType) = innerEncoder.makeData(addHeader: true, isDictionary: false) + self.encoder.encodeInnerObjectData(data, valueType: valueType, forKey: key.stringValue) } else { let typeHash: Int32 = murMurHashString32("\(type(of: value))") let innerEncoder = _AdaptedPostboxEncoder(typeHash: typeHash) try! value.encode(to: innerEncoder) - let (data, valueType) = innerEncoder.makeData(addHeader: true) + let type = type(of: value) + let typeString = "\(type)" + var isDictionary = false + if typeString.hasPrefix("Dictionary<") { + isDictionary = true + } + + let (data, valueType) = innerEncoder.makeData(addHeader: true, isDictionary: isDictionary) + self.encoder.encodeInnerObjectData(data, valueType: valueType, forKey: key.stringValue) } } @@ -65,6 +80,12 @@ extension _AdaptedPostboxEncoder.KeyedContainer: KeyedEncodingContainerProtocol self.encoder.encodeInt64(value, forKey: key.stringValue) } + func encode(_ value: Int, forKey key: Key) throws { + assertionFailure() + + self.encoder.encodeInt32(Int32(value), forKey: key.stringValue) + } + func encode(_ value: Bool, forKey key: Key) throws { self.encoder.encodeBool(value, forKey: key.stringValue) } diff --git a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxSingleValueEncodingContainer.swift b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxSingleValueEncodingContainer.swift index 5ae52729e9..3bba11f5b1 100644 --- a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxSingleValueEncodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxSingleValueEncodingContainer.swift @@ -79,7 +79,7 @@ extension _AdaptedPostboxEncoder.SingleValueContainer: SingleValueEncodingContai } extension _AdaptedPostboxEncoder.SingleValueContainer: AdaptedPostboxEncodingContainer { - func makeData(addHeader: Bool) -> (Data, ValueType) { + func makeData(addHeader: Bool, isDictionary: Bool) -> (Data, ValueType) { preconditionFailure() } } diff --git a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift index 568db0689a..c9dc3ce412 100644 --- a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift @@ -25,7 +25,7 @@ extension _AdaptedPostboxEncoder { self.userInfo = userInfo } - func makeData(addHeader: Bool) -> (Data, ValueType) { + func makeData(addHeader: Bool, isDictionary: Bool) -> (Data, ValueType) { precondition(addHeader) if self.items.isEmpty { @@ -53,7 +53,7 @@ extension _AdaptedPostboxEncoder { buffer.write(&length, offset: 0, length: 4) for case .int64(var value) in self.items { - buffer.write(&value, offset: 0, length: 4) + buffer.write(&value, offset: 0, length: 8) } return (buffer.makeData(), .Int64Array) @@ -75,13 +75,17 @@ extension _AdaptedPostboxEncoder { let buffer = WriteBuffer() var length: Int32 = Int32(self.items.count) + if isDictionary { + precondition(length % 2 == 0) + length /= 2 + } buffer.write(&length, offset: 0, length: 4) for case .object(let data) in self.items { buffer.write(data) } - return (buffer.makeData(), .ObjectArray) + return (buffer.makeData(), isDictionary ? .ObjectDictionary : .ObjectArray) } else if self.items.allSatisfy({ if case .data = $0 { return true } else { return false } }) { let buffer = WriteBuffer() @@ -108,18 +112,28 @@ extension _AdaptedPostboxEncoder.UnkeyedContainer: UnkeyedEncodingContainer { } func encode(_ value: T) throws where T : Encodable { - let typeHash: Int32 = murMurHashString32("\(type(of: value))") + if value is Int32 { + try self.encode(value as! Int32) + } else if value is Int64 { + try self.encode(value as! Int64) + } else if value is String { + try self.encode(value as! String) + } else if value is Data { + try self.encode(value as! Data) + } else { + let typeHash: Int32 = murMurHashString32("\(type(of: value))") - let innerEncoder = _AdaptedPostboxEncoder(typeHash: typeHash) - try! value.encode(to: innerEncoder) + let innerEncoder = _AdaptedPostboxEncoder(typeHash: typeHash) + try! value.encode(to: innerEncoder) - let (data, _) = innerEncoder.makeData(addHeader: true) + let (data, _) = innerEncoder.makeData(addHeader: true, isDictionary: false) - let buffer = WriteBuffer() + let buffer = WriteBuffer() - buffer.write(data) + buffer.write(data) - self.items.append(.object(buffer.makeData())) + self.items.append(.object(buffer.makeData())) + } } func encode(_ value: Int32) throws { diff --git a/submodules/SettingsUI/Sources/Data and Storage/AutodownloadConnectionTypeController.swift b/submodules/SettingsUI/Sources/Data and Storage/AutodownloadConnectionTypeController.swift index 3dd56dfd48..32fab6c784 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/AutodownloadConnectionTypeController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/AutodownloadConnectionTypeController.swift @@ -321,14 +321,14 @@ func autodownloadMediaConnectionTypeController(context: AccountContext, connecti |> deliverOnMainQueue |> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var automaticMediaDownloadSettings: MediaAutoDownloadSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { automaticMediaDownloadSettings = value } else { automaticMediaDownloadSettings = MediaAutoDownloadSettings.defaultSettings } var autodownloadSettings: AutodownloadSettings - if let value = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings { + if let value = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) { autodownloadSettings = value automaticMediaDownloadSettings = automaticMediaDownloadSettings.updatedWithAutodownloadSettings(autodownloadSettings) } else { diff --git a/submodules/SettingsUI/Sources/Data and Storage/AutodownloadMediaCategoryController.swift b/submodules/SettingsUI/Sources/Data and Storage/AutodownloadMediaCategoryController.swift index 9b3ef25c59..a225ee9fa1 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/AutodownloadMediaCategoryController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/AutodownloadMediaCategoryController.swift @@ -388,7 +388,7 @@ func autodownloadMediaCategoryController(context: AccountContext, connectionType return context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]) |> take(1) |> map { sharedData -> MediaAutoDownloadSettings in - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { return value } else { return .defaultSettings @@ -402,14 +402,14 @@ func autodownloadMediaCategoryController(context: AccountContext, connectionType let signal = combineLatest(context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.autodownloadSettings, ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings])) |> deliverOnMainQueue |> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var automaticMediaDownloadSettings: MediaAutoDownloadSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { automaticMediaDownloadSettings = value } else { automaticMediaDownloadSettings = .defaultSettings } var autodownloadSettings: AutodownloadSettings - if let value = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings { + if let value = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) { autodownloadSettings = value automaticMediaDownloadSettings = automaticMediaDownloadSettings.updatedWithAutodownloadSettings(autodownloadSettings) } else { diff --git a/submodules/SettingsUI/Sources/Data and Storage/DataAndStorageSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/DataAndStorageSettingsController.swift index fa1918458e..7b3b219bb9 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/DataAndStorageSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/DataAndStorageSettingsController.swift @@ -561,14 +561,14 @@ public func dataAndStorageController(context: AccountContext, focusOnItemTag: Da dataAndStorageDataPromise.set(context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.autodownloadSettings, ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings, ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings, ApplicationSpecificSharedDataKeys.voiceCallSettings, SharedDataKeys.proxySettings]) |> map { sharedData -> DataAndStorageData in var automaticMediaDownloadSettings: MediaAutoDownloadSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { automaticMediaDownloadSettings = value } else { automaticMediaDownloadSettings = .defaultSettings } var autodownloadSettings: AutodownloadSettings - if let value = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings { + if let value = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) { autodownloadSettings = value automaticMediaDownloadSettings = automaticMediaDownloadSettings.updatedWithAutodownloadSettings(autodownloadSettings) } else { @@ -576,21 +576,21 @@ public func dataAndStorageController(context: AccountContext, focusOnItemTag: Da } let generatedMediaStoreSettings: GeneratedMediaStoreSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings] as? GeneratedMediaStoreSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings]?.get(GeneratedMediaStoreSettings.self) { generatedMediaStoreSettings = value } else { generatedMediaStoreSettings = GeneratedMediaStoreSettings.defaultSettings } let voiceCallSettings: VoiceCallSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) { voiceCallSettings = value } else { voiceCallSettings = VoiceCallSettings.defaultSettings } var proxySettings: ProxySettings? - if let value = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let value = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { proxySettings = value } @@ -682,7 +682,7 @@ public func dataAndStorageController(context: AccountContext, focusOnItemTag: Da contentSettingsConfiguration.get() ) |> map { presentationData, state, dataAndStorageData, sharedData, contentSettingsConfiguration -> (ItemListControllerState, (ItemListNodeState, Any)) in - let webBrowserSettings = (sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings] as? WebBrowserSettings) ?? WebBrowserSettings.defaultSettings + let webBrowserSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings]?.get(WebBrowserSettings.self) ?? WebBrowserSettings.defaultSettings let options = availableOpenInOptions(context: context, item: .url(url: "https://telegram.org")) let defaultWebBrowser: String if let option = options.first(where: { $0.identifier == webBrowserSettings.defaultWebBrowser }) { diff --git a/submodules/SettingsUI/Sources/Data and Storage/IntentsSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/IntentsSettingsController.swift index 755b4e3860..200c1aa23e 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/IntentsSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/IntentsSettingsController.swift @@ -305,7 +305,7 @@ public func intentsSettingsController(context: AccountContext) -> ViewController let signal = combineLatest(context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.intentsSettings]), activeAccountsAndPeers(context: context, includePrimary: true)) |> deliverOnMainQueue |> map { presentationData, sharedData, accounts -> (ItemListControllerState, (ItemListNodeState, Any)) in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings] as? IntentsSettings) ?? IntentsSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings]?.get(IntentsSettings.self) ?? IntentsSettings.defaultSettings let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(presentationData.strings.IntentsSettings_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: intentsSettingsControllerEntries(context: context, presentationData: presentationData, settings: settings, accounts: accounts.1.map { ($0.0.account, $0.1) }), style: .blocks, animateChanges: false) diff --git a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift index 9d46e3f156..6dac2550dd 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift @@ -388,7 +388,7 @@ public func proxySettingsController(accountManager: AccountManager() proxySettings.set(accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> map { sharedData -> ProxySettings in - if let value = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let value = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { return value } else { return ProxySettings.defaultSettings diff --git a/submodules/SettingsUI/Sources/Data and Storage/SaveIncomingMediaController.swift b/submodules/SettingsUI/Sources/Data and Storage/SaveIncomingMediaController.swift index b06e56bfb9..61850cd630 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/SaveIncomingMediaController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/SaveIncomingMediaController.swift @@ -118,7 +118,7 @@ func saveIncomingMediaController(context: AccountContext) -> ViewController { |> deliverOnMainQueue |> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in let automaticMediaDownloadSettings: MediaAutoDownloadSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { automaticMediaDownloadSettings = value } else { automaticMediaDownloadSettings = MediaAutoDownloadSettings.defaultSettings diff --git a/submodules/SettingsUI/Sources/Data and Storage/StorageUsageController.swift b/submodules/SettingsUI/Sources/Data and Storage/StorageUsageController.swift index b5d0018ab7..18a0675ad9 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/StorageUsageController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/StorageUsageController.swift @@ -408,7 +408,7 @@ public func storageUsageController(context: AccountContext, cacheUsagePromise: P cacheSettingsPromise.set(context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.cacheStorageSettings]) |> map { sharedData -> CacheStorageSettings in let cacheSettings: CacheStorageSettings - if let value = sharedData.entries[SharedDataKeys.cacheStorageSettings] as? CacheStorageSettings { + if let value = sharedData.entries[SharedDataKeys.cacheStorageSettings]?.get(CacheStorageSettings.self) { cacheSettings = value } else { cacheSettings = CacheStorageSettings.defaultSettings diff --git a/submodules/SettingsUI/Sources/Data and Storage/VoiceCallDataSavingController.swift b/submodules/SettingsUI/Sources/Data and Storage/VoiceCallDataSavingController.swift index fe684bb32e..2fd37c6d3e 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/VoiceCallDataSavingController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/VoiceCallDataSavingController.swift @@ -125,14 +125,14 @@ func voiceCallDataSavingController(context: AccountContext) -> ViewController { let sharedSettings = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.voiceCallSettings]) |> map { sharedData -> (VoiceCallSettings, AutodownloadSettings) in let voiceCallSettings: VoiceCallSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) { voiceCallSettings = value } else { voiceCallSettings = VoiceCallSettings.defaultSettings } let autodownloadSettings: AutodownloadSettings - if let value = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings { + if let value = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) { autodownloadSettings = value } else { autodownloadSettings = AutodownloadSettings.defaultSettings diff --git a/submodules/SettingsUI/Sources/Data and Storage/WebBrowserSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/WebBrowserSettingsController.swift index 02ee92d985..cf9b815d8c 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/WebBrowserSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/WebBrowserSettingsController.swift @@ -103,7 +103,7 @@ public func webBrowserSettingsController(context: AccountContext) -> ViewControl let signal = combineLatest(context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.webBrowserSettings])) |> deliverOnMainQueue |> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings] as? WebBrowserSettings) ?? WebBrowserSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings]?.get(WebBrowserSettings.self) ?? WebBrowserSettings.defaultSettings let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(presentationData.strings.WebBrowser_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: webBrowserSettingsControllerEntries(context: context, presentationData: presentationData, selectedBrowser: settings.defaultWebBrowser), style: .blocks, animateChanges: false) diff --git a/submodules/SettingsUI/Sources/Language Selection/LocalizationListControllerNode.swift b/submodules/SettingsUI/Sources/Language Selection/LocalizationListControllerNode.swift index 6eee101e54..334e236664 100644 --- a/submodules/SettingsUI/Sources/Language Selection/LocalizationListControllerNode.swift +++ b/submodules/SettingsUI/Sources/Language Selection/LocalizationListControllerNode.swift @@ -338,9 +338,9 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { let removeItem: (String) -> Void = { id in let _ = (context.account.postbox.transaction { transaction -> Signal in removeSavedLocalization(transaction: transaction, languageCode: id) - let state = transaction.getPreferencesEntry(key: PreferencesKeys.localizationListState) as? LocalizationListState + let state = transaction.getPreferencesEntry(key: PreferencesKeys.localizationListState)?.get(LocalizationListState.self) return context.sharedContext.accountManager.transaction { transaction -> LocalizationInfo? in - if let settings = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings, let state = state { + if let settings = transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self), let state = state { if settings.primaryComponent.languageCode == id { for item in state.availableOfficialLocalizations { if item.languageCode == "en" { @@ -374,12 +374,12 @@ final class LocalizationListControllerNode: ViewControllerTracingNode { var entries: [LanguageListEntry] = [] var activeLanguageCode: String? - if let localizationSettings = sharedData.entries[SharedDataKeys.localizationSettings] as? LocalizationSettings { + if let localizationSettings = sharedData.entries[SharedDataKeys.localizationSettings]?.get(LocalizationSettings.self) { activeLanguageCode = localizationSettings.primaryComponent.languageCode } var existingIds = Set() - let localizationListState = (view.views[preferencesKey] as? PreferencesView)?.values[PreferencesKeys.localizationListState] as? LocalizationListState + let localizationListState = (view.views[preferencesKey] as? PreferencesView)?.values[PreferencesKeys.localizationListState]?.get(LocalizationListState.self) if let localizationListState = localizationListState, !localizationListState.availableOfficialLocalizations.isEmpty { strongSelf.currentListState = localizationListState diff --git a/submodules/SettingsUI/Sources/Notifications/Exceptions/NotificationExceptionSettingsController.swift b/submodules/SettingsUI/Sources/Notifications/Exceptions/NotificationExceptionSettingsController.swift index 9638dd5ef2..5813c3dc1c 100644 --- a/submodules/SettingsUI/Sources/Notifications/Exceptions/NotificationExceptionSettingsController.swift +++ b/submodules/SettingsUI/Sources/Notifications/Exceptions/NotificationExceptionSettingsController.swift @@ -351,7 +351,7 @@ public func notificationPeerExceptionController(context: AccountContext, peer: P statePromise.set(context.account.postbox.transaction { transaction -> NotificationExceptionPeerState in var state = NotificationExceptionPeerState(canRemove: mode.peerIds.contains(peer.id), notifications: transaction.getPeerNotificationSettings(peer.id) as? TelegramPeerNotificationSettings) - let globalSettings: GlobalNotificationSettings = (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings) ?? GlobalNotificationSettings.defaultSettings + let globalSettings: GlobalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) ?? GlobalNotificationSettings.defaultSettings switch mode { case .channels: state = state.withUpdatedDefaultSound(globalSettings.effective.channels.sound) diff --git a/submodules/SettingsUI/Sources/Notifications/NotificationsAndSounds.swift b/submodules/SettingsUI/Sources/Notifications/NotificationsAndSounds.swift index 27412b4a81..2cb49c5ecb 100644 --- a/submodules/SettingsUI/Sources/Notifications/NotificationsAndSounds.swift +++ b/submodules/SettingsUI/Sources/Notifications/NotificationsAndSounds.swift @@ -1077,14 +1077,14 @@ public func notificationsAndSoundsController(context: AccountContext, exceptions |> map { presentationData, sharedData, view, exceptions, authorizationStatus, warningSuppressed, hasMoreThanOneAccount -> (ItemListControllerState, (ItemListNodeState, Any)) in let viewSettings: GlobalNotificationSettingsSet - if let settings = view.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = view.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { viewSettings = settings.effective } else { viewSettings = GlobalNotificationSettingsSet.defaultSettings } let inAppSettings: InAppNotificationSettings - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) { inAppSettings = settings } else { inAppSettings = InAppNotificationSettings.defaultSettings diff --git a/submodules/SettingsUI/Sources/Privacy and Security/DataPrivacySettingsController.swift b/submodules/SettingsUI/Sources/Privacy and Security/DataPrivacySettingsController.swift index 755ce09724..be32e52dcf 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/DataPrivacySettingsController.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/DataPrivacySettingsController.swift @@ -419,9 +419,9 @@ public func dataPrivacyController(context: AccountContext) -> ViewController { let _ = context.account.postbox.transaction({ transaction in transaction.updatePreferencesEntry(key: PreferencesKeys.contactsSettings, { current in - var settings = current as? ContactsSettings ?? ContactsSettings.defaultSettings + var settings = current?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings settings.synchronizeContacts = false - return settings + return PreferencesEntry(settings) }) }).start() @@ -440,9 +440,9 @@ public func dataPrivacyController(context: AccountContext) -> ViewController { }, updateSyncContacts: { value in let _ = context.account.postbox.transaction({ transaction in transaction.updatePreferencesEntry(key: PreferencesKeys.contactsSettings, { current in - var settings = current as? ContactsSettings ?? ContactsSettings.defaultSettings + var settings = current?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings settings.synchronizeContacts = value - return settings + return PreferencesEntry(settings) }) }).start() }, updateSuggestFrequentContacts: { value in @@ -506,7 +506,7 @@ public func dataPrivacyController(context: AccountContext) -> ViewController { |> map { presentationData, state, noticeView, sharedData, preferences, recentPeers -> (ItemListControllerState, (ItemListNodeState, Any)) in let secretChatLinkPreviews = noticeView.value.flatMap({ ApplicationSpecificNotice.getSecretChatLinkPreviews($0) }) - let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings] as? ContactsSettings ?? ContactsSettings.defaultSettings + let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings]?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings let synchronizeDeviceContacts: Bool = settings.synchronizeContacts diff --git a/submodules/SettingsUI/Sources/Privacy and Security/PasscodeOptionsController.swift b/submodules/SettingsUI/Sources/Privacy and Security/PasscodeOptionsController.swift index 0d0814e639..5d34e5e2f6 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/PasscodeOptionsController.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/PasscodeOptionsController.swift @@ -220,7 +220,7 @@ func passcodeOptionsController(context: AccountContext) -> ViewController { let passcodeOptionsDataPromise = Promise() passcodeOptionsDataPromise.set(context.sharedContext.accountManager.transaction { transaction -> (PostboxAccessChallengeData, PresentationPasscodeSettings) in - let passcodeSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings) as? PresentationPasscodeSettings ?? PresentationPasscodeSettings.defaultSettings + let passcodeSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings)?.get(PresentationPasscodeSettings.self) ?? PresentationPasscodeSettings.defaultSettings return (transaction.getAccessChallengeData(), passcodeSettings) } |> map { accessChallenge, passcodeSettings -> PasscodeOptionsData in @@ -444,7 +444,7 @@ public func passcodeEntryController(context: AccountContext, animateIn: Bool = t } |> mapToSignal { accessChallengeData -> Signal<(PostboxAccessChallengeData, PresentationPasscodeSettings?), NoError> in return context.sharedContext.accountManager.transaction { transaction -> (PostboxAccessChallengeData, PresentationPasscodeSettings?) in - let passcodeSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings) as? PresentationPasscodeSettings + let passcodeSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings)?.get(PresentationPasscodeSettings.self) return (accessChallengeData, passcodeSettings) } } diff --git a/submodules/SettingsUI/Sources/Privacy and Security/PrivacyAndSecurityController.swift b/submodules/SettingsUI/Sources/Privacy and Security/PrivacyAndSecurityController.swift index 7be99cbb75..3dbf6ebb52 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/PrivacyAndSecurityController.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/PrivacyAndSecurityController.swift @@ -616,8 +616,8 @@ public func privacyAndSecurityController(context: AccountContext, initialSetting let callsSignal = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.voiceCallSettings]), context.account.postbox.preferencesView(keys: [PreferencesKeys.voipConfiguration])) |> take(1) |> map { sharedData, view -> (VoiceCallSettings, VoipConfiguration) in - let voiceCallSettings: VoiceCallSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings ?? .defaultSettings - let voipConfiguration = view.values[PreferencesKeys.voipConfiguration] as? VoipConfiguration ?? .defaultValue + let voiceCallSettings: VoiceCallSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? .defaultSettings + let voipConfiguration = view.values[PreferencesKeys.voipConfiguration]?.get(VoipConfiguration.self) ?? .defaultValue return (voiceCallSettings, voipConfiguration) } @@ -850,7 +850,7 @@ public func privacyAndSecurityController(context: AccountContext, initialSetting let signal = combineLatest(queue: .mainQueue(), context.sharedContext.presentationData, statePromise.get(), privacySettingsPromise.get(), context.sharedContext.accountManager.noticeEntry(key: ApplicationSpecificNotice.secretChatLinkPreviewsKey()), context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]), context.engine.peers.recentPeers(), blockedPeersState.get(), webSessionsContext.state, context.sharedContext.accountManager.accessChallengeData(), combineLatest(twoStepAuth.get(), twoStepAuthDataValue.get()), context.account.postbox.combinedView(keys: [preferencesKey])) |> map { presentationData, state, privacySettings, noticeView, sharedData, recentPeers, blockedPeersState, activeWebsitesState, accessChallengeData, twoStepAuth, preferences -> (ItemListControllerState, (ItemListNodeState, Any)) in var canAutoarchive = false - if let view = preferences.views[preferencesKey] as? PreferencesView, let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration, let data = appConfiguration.data, let hasAutoarchive = data["autoarchive_setting_available"] as? Bool { + if let view = preferences.views[preferencesKey] as? PreferencesView, let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self), let data = appConfiguration.data, let hasAutoarchive = data["autoarchive_setting_available"] as? Bool { canAutoarchive = hasAutoarchive } diff --git a/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift b/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift index b7671b73fe..077b146e40 100644 --- a/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift +++ b/submodules/SettingsUI/Sources/Privacy and Security/Recent Sessions/RecentSessionsController.swift @@ -639,7 +639,7 @@ public func recentSessionsController(context: AccountContext, activeSessionsCont let enableQRLogin = context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { view -> Bool in - guard let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration else { + guard let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { return false } guard let data = appConfiguration.data, let enableQR = data["qr_login_camera"] as? Bool, enableQR else { diff --git a/submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift b/submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift index 9f5c93c37f..2f66459456 100644 --- a/submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift +++ b/submodules/SettingsUI/Sources/Search/SettingsSearchableItems.swift @@ -436,8 +436,8 @@ private func privacySearchableItems(context: AccountContext, privacySettings: Ac callsSignal = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.voiceCallSettings]), context.account.postbox.preferencesView(keys: [PreferencesKeys.voipConfiguration])) |> take(1) |> map { sharedData, view -> (VoiceCallSettings, VoipConfiguration)? in - let voiceCallSettings: VoiceCallSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings ?? .defaultSettings - let voipConfiguration = view.values[PreferencesKeys.voipConfiguration] as? VoipConfiguration ?? .defaultValue + let voiceCallSettings: VoiceCallSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? .defaultSettings + let voipConfiguration = view.values[PreferencesKeys.voipConfiguration]?.get(VoipConfiguration.self) ?? .defaultValue return (voiceCallSettings, voipConfiguration) } } else { @@ -742,7 +742,7 @@ func settingsSearchableItems(context: AccountContext, notificationExceptionsList |> take(1) |> map { view -> GlobalNotificationSettingsSet in let viewSettings: GlobalNotificationSettingsSet - if let settings = view.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = view.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { viewSettings = settings.effective } else { viewSettings = GlobalNotificationSettingsSet.defaultSettings @@ -758,7 +758,7 @@ func settingsSearchableItems(context: AccountContext, notificationExceptionsList let proxyServers = context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> map { sharedData -> ProxySettings in - if let value = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let value = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { return value } else { return ProxySettings.defaultSettings @@ -771,13 +771,13 @@ func settingsSearchableItems(context: AccountContext, notificationExceptionsList let localizationPreferencesKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.localizationListState])) let localizations = combineLatest(context.account.postbox.combinedView(keys: [localizationPreferencesKey]), context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.localizationSettings])) |> map { view, sharedData -> [LocalizationInfo] in - if let localizationListState = (view.views[localizationPreferencesKey] as? PreferencesView)?.values[PreferencesKeys.localizationListState] as? LocalizationListState, !localizationListState.availableOfficialLocalizations.isEmpty { + if let localizationListState = (view.views[localizationPreferencesKey] as? PreferencesView)?.values[PreferencesKeys.localizationListState]?.get(LocalizationListState.self), !localizationListState.availableOfficialLocalizations.isEmpty { var existingIds = Set() let availableSavedLocalizations = localizationListState.availableSavedLocalizations.filter({ info in !localizationListState.availableOfficialLocalizations.contains(where: { $0.languageCode == info.languageCode }) }) var activeLanguageCode: String? - if let localizationSettings = sharedData.entries[SharedDataKeys.localizationSettings] as? LocalizationSettings { + if let localizationSettings = sharedData.entries[SharedDataKeys.localizationSettings]?.get(LocalizationSettings.self) { activeLanguageCode = localizationSettings.primaryComponent.languageCode } diff --git a/submodules/SettingsUI/Sources/Stickers/ArchivedStickerPacksController.swift b/submodules/SettingsUI/Sources/Stickers/ArchivedStickerPacksController.swift index bd86306f87..f2c88adb1e 100644 --- a/submodules/SettingsUI/Sources/Stickers/ArchivedStickerPacksController.swift +++ b/submodules/SettingsUI/Sources/Stickers/ArchivedStickerPacksController.swift @@ -378,7 +378,7 @@ public func archivedStickerPacksController(context: AccountContext, mode: Archiv |> deliverOnMainQueue |> map { presentationData, state, packs, installedView, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } diff --git a/submodules/SettingsUI/Sources/Stickers/FeaturedStickerPacksController.swift b/submodules/SettingsUI/Sources/Stickers/FeaturedStickerPacksController.swift index 3d17794f75..aac83cf4fb 100644 --- a/submodules/SettingsUI/Sources/Stickers/FeaturedStickerPacksController.swift +++ b/submodules/SettingsUI/Sources/Stickers/FeaturedStickerPacksController.swift @@ -191,7 +191,7 @@ public func featuredStickerPacksController(context: AccountContext) -> ViewContr |> deliverOnMainQueue |> map { presentationData, state, view, featured, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } diff --git a/submodules/SettingsUI/Sources/Stickers/InstalledStickerPacksController.swift b/submodules/SettingsUI/Sources/Stickers/InstalledStickerPacksController.swift index bf40f089ae..39977f31bd 100644 --- a/submodules/SettingsUI/Sources/Stickers/InstalledStickerPacksController.swift +++ b/submodules/SettingsUI/Sources/Stickers/InstalledStickerPacksController.swift @@ -644,7 +644,7 @@ public func installedStickerPacksController(context: AccountContext, mode: Insta |> deliverOnMainQueue |> map { presentationData, state, view, temporaryPackOrder, featuredAndArchived, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } diff --git a/submodules/SettingsUI/Sources/Themes/ThemeAccentColorController.swift b/submodules/SettingsUI/Sources/Themes/ThemeAccentColorController.swift index 62f2e4888b..37d636eab6 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeAccentColorController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeAccentColorController.swift @@ -368,7 +368,7 @@ final class ThemeAccentColorController: ViewController { guard let strongSelf = self else { return } - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let accentColor: UIColor var initialWallpaper: TelegramWallpaper? diff --git a/submodules/SettingsUI/Sources/Themes/ThemeAutoNightSettingsController.swift b/submodules/SettingsUI/Sources/Themes/ThemeAutoNightSettingsController.swift index 2064eeab5f..7d62ed2119 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeAutoNightSettingsController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeAutoNightSettingsController.swift @@ -369,7 +369,7 @@ public func themeAutoNightSettingsController(context: AccountContext) -> ViewCon let _ = (combineLatest(stagingSettingsPromise.get(), sharedData) |> take(1) |> deliverOnMainQueue).start(next: { stagingSettings, sharedData in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let updated = f(stagingSettings ?? settings.automaticThemeSwitchSetting) stagingSettingsPromise.set(updated) if areSettingsValid(updated) { @@ -569,7 +569,7 @@ public func themeAutoNightSettingsController(context: AccountContext) -> ViewCon let signal = combineLatest(context.sharedContext.presentationData |> deliverOnMainQueue, sharedData |> deliverOnMainQueue, cloudThemes.get() |> deliverOnMainQueue, stagingSettingsPromise.get() |> deliverOnMainQueue) |> map { presentationData, sharedData, cloudThemes, stagingSettings -> (ItemListControllerState, (ItemListNodeState, Any)) in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let defaultThemes: [PresentationThemeReference] = [.builtin(.night), .builtin(.nightAccent)] let cloudThemes: [PresentationThemeReference] = cloudThemes.map { .cloud(PresentationCloudTheme(theme: $0, resolvedWallpaper: nil, creatorAccountId: $0.isCreator ? context.account.id : nil)) } diff --git a/submodules/SettingsUI/Sources/Themes/ThemeColorsGridController.swift b/submodules/SettingsUI/Sources/Themes/ThemeColorsGridController.swift index 54640c18c0..563df18433 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeColorsGridController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeColorsGridController.swift @@ -182,7 +182,7 @@ final class ThemeColorsGridController: ViewController { guard let strongSelf = self else { return } - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let autoNightModeTriggered = strongSelf.presentationData.autoNightModeTriggered let themeReference: PresentationThemeReference diff --git a/submodules/SettingsUI/Sources/Themes/ThemeGridControllerNode.swift b/submodules/SettingsUI/Sources/Themes/ThemeGridControllerNode.swift index 762f26a144..cb9dd1e9f7 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeGridControllerNode.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeGridControllerNode.swift @@ -504,7 +504,7 @@ final class ThemeGridControllerNode: ASDisplayNode { self.context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.wallapersState]) ) |> map { remoteWallpapers, sharedData -> [Wallpaper] in - let localState = (sharedData.entries[SharedDataKeys.wallapersState] as? WallpapersState) ?? WallpapersState.default + let localState = sharedData.entries[SharedDataKeys.wallapersState]?.get(WallpapersState.self) ?? WallpapersState.default var wallpapers: [Wallpaper] = [] for wallpaper in localState.wallpapers { diff --git a/submodules/SettingsUI/Sources/Themes/ThemePreviewController.swift b/submodules/SettingsUI/Sources/Themes/ThemePreviewController.swift index 8feb895a04..3fdbcd6e6c 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemePreviewController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemePreviewController.swift @@ -356,7 +356,7 @@ public final class ThemePreviewController: ViewController { var previousDefaultTheme: (PresentationThemeReference, PresentationThemeAccentColor?, Bool, PresentationThemeReference, Bool)? transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings, { entry in let currentSettings: PresentationThemeSettings - if let entry = entry as? PresentationThemeSettings { + if let entry = entry?.get(PresentationThemeSettings.self) { currentSettings = entry } else { currentSettings = PresentationThemeSettings.defaultSettings @@ -387,7 +387,7 @@ public final class ThemePreviewController: ViewController { var themeSpecificChatWallpapers = updatedSettings.themeSpecificChatWallpapers themeSpecificChatWallpapers[updatedTheme.index] = nil - return updatedSettings.withUpdatedThemeSpecificChatWallpapers(themeSpecificChatWallpapers).withUpdatedThemeSpecificAccentColors(themeSpecificAccentColors) + return PreferencesEntry(updatedSettings.withUpdatedThemeSpecificChatWallpapers(themeSpecificChatWallpapers).withUpdatedThemeSpecificAccentColors(themeSpecificAccentColors)) }) return previousDefaultTheme } diff --git a/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift b/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift index 025604f09a..5cf7242638 100644 --- a/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift +++ b/submodules/SettingsUI/Sources/Themes/ThemeSettingsController.swift @@ -600,14 +600,14 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The let _ = (context.sharedContext.accountManager.sharedData(keys: Set([ApplicationSpecificSharedDataKeys.presentationThemeSettings])) |> take(1) |> deliverOnMainQueue).start(next: { view in - let settings = (view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings pushControllerImpl?(TextSizeSelectionController(context: context, presentationThemeSettings: settings)) }) }, openBubbleSettings: { let _ = (context.sharedContext.accountManager.sharedData(keys: Set([ApplicationSpecificSharedDataKeys.presentationThemeSettings])) |> take(1) |> deliverOnMainQueue).start(next: { view in - let settings = (view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = view.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings pushControllerImpl?(BubbleSettingsController(context: context, presentationThemeSettings: settings)) }) }, toggleLargeEmoji: { largeEmoji in @@ -631,7 +631,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The pushControllerImpl?(controller) }, themeContextAction: { isCurrent, reference, node, gesture in let _ = (context.sharedContext.accountManager.transaction { transaction -> (PresentationThemeAccentColor?, TelegramWallpaper?) in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings) as? PresentationThemeSettings ?? PresentationThemeSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let accentColor = settings.themeSpecificAccentColors[reference.index] var wallpaper: TelegramWallpaper? if let accentColor = accentColor { @@ -808,7 +808,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The }) }, colorContextAction: { isCurrent, reference, accentColor, node, gesture in let _ = (context.sharedContext.accountManager.transaction { transaction -> (ThemeSettingsColorOption?, TelegramWallpaper?) in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings) as? PresentationThemeSettings ?? PresentationThemeSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings var wallpaper: TelegramWallpaper? if let accentColor = accentColor { switch accentColor { @@ -1041,7 +1041,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The let signal = combineLatest(queue: .mainQueue(), context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.presentationThemeSettings]), cloudThemes.get(), availableAppIcons, currentAppIconName.get(), removedThemeIndexesPromise.get()) |> map { presentationData, sharedData, cloudThemes, availableAppIcons, currentAppIconName, removedThemeIndexes -> (ItemListControllerState, (ItemListNodeState, Any)) in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let themeReference: PresentationThemeReference if presentationData.autoNightModeTriggered { @@ -1189,7 +1189,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The let _ = applyTheme(accountManager: context.sharedContext.accountManager, account: context.account, theme: cloudTheme).start() let currentTheme = context.sharedContext.accountManager.transaction { transaction -> (PresentationThemeReference) in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings) as? PresentationThemeSettings ?? PresentationThemeSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings if autoNightModeTriggered { return settings.automaticThemeSwitchSetting.theme } else { @@ -1322,7 +1322,7 @@ public func themeSettingsController(context: AccountContext, focusOnItemTag: The actionSheet?.dismissAnimated() let _ = (context.sharedContext.accountManager.transaction { transaction -> PresentationThemeReference in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings) as? PresentationThemeSettings ?? PresentationThemeSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings let themeReference: PresentationThemeReference let autoNightModeTriggered = context.sharedContext.currentPresentationData.with { $0 }.autoNightModeTriggered diff --git a/submodules/SettingsUI/Sources/Watch/WatchSettingsController.swift b/submodules/SettingsUI/Sources/Watch/WatchSettingsController.swift index 3584a1b00d..e863dd1dae 100644 --- a/submodules/SettingsUI/Sources/Watch/WatchSettingsController.swift +++ b/submodules/SettingsUI/Sources/Watch/WatchSettingsController.swift @@ -129,7 +129,7 @@ public func watchSettingsController(context: AccountContext) -> ViewController { let signal = combineLatest(context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.watchPresetSettings])) |> deliverOnMainQueue |> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.watchPresetSettings] as? WatchPresetSettings) ?? WatchPresetSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.watchPresetSettings]?.get(WatchPresetSettings.self) ?? WatchPresetSettings.defaultSettings let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(presentationData.strings.AppleWatch_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back)) let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: watchSettingsControllerEntries(presentationData: presentationData, customPresets: settings.customPresets), style: .blocks, animateChanges: false) diff --git a/submodules/StickerPackPreviewUI/Sources/StickerPackPreviewController.swift b/submodules/StickerPackPreviewUI/Sources/StickerPackPreviewController.swift index cfddc92382..93161b1a19 100644 --- a/submodules/StickerPackPreviewUI/Sources/StickerPackPreviewController.swift +++ b/submodules/StickerPackPreviewUI/Sources/StickerPackPreviewController.swift @@ -173,7 +173,7 @@ public final class StickerPackPreviewController: ViewController, StandalonePrese self.stickerPackDisposable.set((combineLatest(self.stickerPackContents.get(), self.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.stickerSettings]) |> take(1)) |> mapToSignal { next, sharedData -> Signal<(LoadedStickerPack, StickerSettings), NoError> in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } diff --git a/submodules/TelegramBaseController/Sources/TelegramBaseController.swift b/submodules/TelegramBaseController/Sources/TelegramBaseController.swift index a1848a92fe..a9750aba2b 100644 --- a/submodules/TelegramBaseController/Sources/TelegramBaseController.swift +++ b/submodules/TelegramBaseController/Sources/TelegramBaseController.swift @@ -676,10 +676,10 @@ open class TelegramBaseController: ViewController, KeyShortcutResponder { return } let _ = (strongSelf.context.sharedContext.accountManager.transaction { transaction -> AudioPlaybackRate in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings) as? MusicPlaybackSettings ?? MusicPlaybackSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings)?.get(MusicPlaybackSettings.self) ?? MusicPlaybackSettings.defaultSettings transaction.updateSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings, { _ in - return settings.withUpdatedVoicePlaybackRate(rate) + return PreferencesEntry(settings.withUpdatedVoicePlaybackRate(rate)) }) return rate } diff --git a/submodules/TelegramCallsUI/Sources/CallController.swift b/submodules/TelegramCallsUI/Sources/CallController.swift index dc1a46bbf3..5845fc5d36 100644 --- a/submodules/TelegramCallsUI/Sources/CallController.swift +++ b/submodules/TelegramCallsUI/Sources/CallController.swift @@ -274,7 +274,7 @@ public final class CallController: ViewController { let _ = (combineLatest(strongSelf.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.callListSettings]), ApplicationSpecificNotice.getCallsTabTip(accountManager: strongSelf.sharedContext.accountManager)) |> map { sharedData, callsTabTip -> Int32 in var value = false - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings] as? CallListSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings]?.get(CallListSettings.self) { value = settings.showTab } if value { diff --git a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift index f1ddbbb019..07c4eb7ba1 100644 --- a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift +++ b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift @@ -149,7 +149,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { let enableCallKit = accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.voiceCallSettings]) |> map { sharedData -> Bool in - let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings ?? .defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? .defaultSettings return settings.enableSystemIntegration } |> distinctUntilChanged @@ -245,7 +245,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { self.proxyServerDisposable = (accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> deliverOnMainQueue).start(next: { [weak self] sharedData in - if let strongSelf = self, let settings = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let strongSelf = self, let settings = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { if settings.enabled && settings.useForCalls { strongSelf.proxyServer = settings.activeServer } else { @@ -257,7 +257,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { self.callSettingsDisposable = (accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.voiceCallSettings]) |> deliverOnMainQueue).start(next: { [weak self] sharedData in if let strongSelf = self { - strongSelf.callSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings] as? VoiceCallSettings ?? .defaultSettings + strongSelf.callSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? .defaultSettings } }) } @@ -281,11 +281,11 @@ public final class PresentationCallManagerImpl: PresentationCallManager { return } - let configuration = preferences.values[PreferencesKeys.voipConfiguration] as? VoipConfiguration ?? .defaultValue - let derivedState = preferences.values[ApplicationSpecificPreferencesKeys.voipDerivedState] as? VoipDerivedState ?? .default - let autodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings ?? .defaultSettings - let experimentalSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings] as? ExperimentalUISettings ?? .defaultSettings - let appConfiguration = preferences.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? AppConfiguration.defaultValue + let configuration = preferences.values[PreferencesKeys.voipConfiguration]?.get(VoipConfiguration.self) ?? .defaultValue + let derivedState = preferences.values[ApplicationSpecificPreferencesKeys.voipDerivedState]?.get(VoipDerivedState.self) ?? .default + let autodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) ?? .defaultSettings + let experimentalSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings]?.get(ExperimentalUISettings.self) ?? .defaultSettings + let appConfiguration = preferences.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue let call = PresentationCallImpl( context: firstState.0, @@ -486,7 +486,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { } let request = context.account.postbox.transaction { transaction -> (VideoCallsConfiguration, CachedUserData?) in - let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration) as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue return (VideoCallsConfiguration(appConfiguration: appConfiguration), transaction.getPeerCachedData(peerId: peerId) as? CachedUserData) } |> mapToSignal { callsConfiguration, cachedUserData -> Signal in @@ -521,10 +521,10 @@ public final class PresentationCallManagerImpl: PresentationCallManager { currentCall.rejectBusy() } - let configuration = preferences.values[PreferencesKeys.voipConfiguration] as? VoipConfiguration ?? .defaultValue - let derivedState = preferences.values[ApplicationSpecificPreferencesKeys.voipDerivedState] as? VoipDerivedState ?? .default - let autodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings ?? .defaultSettings - let appConfiguration = preferences.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? AppConfiguration.defaultValue + let configuration = preferences.values[PreferencesKeys.voipConfiguration]?.get(VoipConfiguration.self) ?? .defaultValue + let derivedState = preferences.values[ApplicationSpecificPreferencesKeys.voipDerivedState]?.get(VoipDerivedState.self) ?? .default + let autodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) ?? .defaultSettings + let appConfiguration = preferences.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue let callsConfiguration = VideoCallsConfiguration(appConfiguration: appConfiguration) var isVideoPossible: Bool @@ -541,7 +541,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { isVideoPossible = false } - let experimentalSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings] as? ExperimentalUISettings ?? .defaultSettings + let experimentalSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings]?.get(ExperimentalUISettings.self) ?? .defaultSettings let call = PresentationCallImpl( context: context, diff --git a/submodules/TelegramCallsUI/Sources/VoiceChatController.swift b/submodules/TelegramCallsUI/Sources/VoiceChatController.swift index 022c0d24ef..303f4211d7 100644 --- a/submodules/TelegramCallsUI/Sources/VoiceChatController.swift +++ b/submodules/TelegramCallsUI/Sources/VoiceChatController.swift @@ -1899,7 +1899,7 @@ public final class VoiceChatController: ViewController { return } - let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue let configuration = VoiceChatConfiguration.with(appConfiguration: appConfiguration) strongSelf.configuration = configuration diff --git a/submodules/TelegramCore/BUILD b/submodules/TelegramCore/BUILD index f3c1fbc643..28436f87e6 100644 --- a/submodules/TelegramCore/BUILD +++ b/submodules/TelegramCore/BUILD @@ -6,6 +6,9 @@ swift_library( srcs = glob([ "Sources/**/*.swift", ]), + copts = [ + "-warnings-as-errors", + ], deps = [ "//submodules/TelegramApi:TelegramApi", "//submodules/MtProtoKit:MtProtoKit", diff --git a/submodules/TelegramCore/Sources/Account/Account.swift b/submodules/TelegramCore/Sources/Account/Account.swift index f514da28e5..dcb0ea6f78 100644 --- a/submodules/TelegramCore/Sources/Account/Account.swift +++ b/submodules/TelegramCore/Sources/Account/Account.swift @@ -129,11 +129,11 @@ public class UnauthorizedAccount { let keychain = makeExclusiveKeychain(id: self.id, postbox: self.postbox) return accountManager.transaction { transaction -> (LocalizationSettings?, ProxySettings?) in - return (transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings, transaction.getSharedData(SharedDataKeys.proxySettings) as? ProxySettings) + return (transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self), transaction.getSharedData(SharedDataKeys.proxySettings)?.get(ProxySettings.self)) } |> mapToSignal { localizationSettings, proxySettings -> Signal<(LocalizationSettings?, ProxySettings?, NetworkSettings?), NoError> in return self.postbox.transaction { transaction -> (LocalizationSettings?, ProxySettings?, NetworkSettings?) in - return (localizationSettings, proxySettings, transaction.getPreferencesEntry(key: PreferencesKeys.networkSettings) as? NetworkSettings) + return (localizationSettings, proxySettings, transaction.getPreferencesEntry(key: PreferencesKeys.networkSettings)?.get(NetworkSettings.self)) } } |> mapToSignal { (localizationSettings, proxySettings, networkSettings) -> Signal in @@ -251,7 +251,7 @@ public func accountWithId(accountManager: AccountManager (LocalizationSettings?, ProxySettings?) in - return (transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings, transaction.getSharedData(SharedDataKeys.proxySettings) as? ProxySettings) + return (transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self), transaction.getSharedData(SharedDataKeys.proxySettings)?.get(ProxySettings.self)) } |> mapToSignal { localizationSettings, proxySettings -> Signal in return postbox.transaction { transaction -> (PostboxCoding?, LocalizationSettings?, ProxySettings?, NetworkSettings?) in @@ -266,7 +266,7 @@ public func accountWithId(accountManager: AccountManager mapToSignal { (accountState, localizationSettings, proxySettings, networkSettings) -> Signal in let keychain = makeExclusiveKeychain(id: id, postbox: postbox) @@ -407,7 +407,8 @@ func _internal_twoStepAuthData(_ network: Network) -> Signal String { let hexString = NSMutableString() - data.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + data.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) for i in 0 ..< data.count { hexString.appendFormat("%02x", UInt(bytes.advanced(by: i).pointee)) } @@ -437,19 +438,22 @@ public func dataWithHexString(_ string: String) -> Data { } func sha1Digest(_ data : Data) -> Data { - return data.withUnsafeBytes { bytes -> Data in + return data.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress! return CryptoSHA1(bytes, Int32(data.count)) } } func sha256Digest(_ data : Data) -> Data { - return data.withUnsafeBytes { bytes -> Data in + return data.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress! return CryptoSHA256(bytes, Int32(data.count)) } } func sha512Digest(_ data : Data) -> Data { - return data.withUnsafeBytes { bytes -> Data in + return data.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress! return CryptoSHA512(bytes, Int32(data.count)) } } @@ -466,7 +470,8 @@ func passwordUpdateKDF(encryptionProvider: EncryptionProvider, password: String, var nextSalt1 = salt1 var randomSalt1 = Data() randomSalt1.count = 32 - randomSalt1.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + randomSalt1.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) arc4random_buf(bytes, 32) } nextSalt1.append(randomSalt1) @@ -474,7 +479,8 @@ func passwordUpdateKDF(encryptionProvider: EncryptionProvider, password: String, let nextSalt2 = salt2 var g = Data(count: 4) - g.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + g.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) var gValue = gValue withUnsafeBytes(of: &gValue, { (sourceBuffer: UnsafeRawBufferPointer) -> Void in let sourceBytes = sourceBuffer.bindMemory(to: Int8.self).baseAddress! @@ -526,8 +532,10 @@ private func paddedXor(_ a: Data, _ b: Data) -> Data { while b.count < count { b.insert(0, at: 0) } - a.withUnsafeMutableBytes { (aBytes: UnsafeMutablePointer) -> Void in - b.withUnsafeBytes { (bBytes: UnsafePointer) -> Void in + a.withUnsafeMutableBytes { rawABytes -> Void in + let aBytes = rawABytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + b.withUnsafeBytes { rawBBytes -> Void in + let bBytes = rawBBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) for i in 0 ..< count { aBytes.advanced(by: i).pointee = aBytes.advanced(by: i).pointee ^ bBytes.advanced(by: i).pointee } @@ -547,12 +555,14 @@ func passwordKDF(encryptionProvider: EncryptionProvider, password: String, deriv case let .sha256_sha256_PBKDF2_HMAC_sha512_sha256_srp(salt1, salt2, iterations, gValue, p): var a = Data(count: p.count) let aLength = a.count - a.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + a.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) let _ = SecRandomCopyBytes(nil, aLength, bytes) } var g = Data(count: 4) - g.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + g.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) var gValue = gValue withUnsafeBytes(of: &gValue, { (sourceBuffer: UnsafeRawBufferPointer) -> Void in let sourceBytes = sourceBuffer.bindMemory(to: Int8.self).baseAddress! @@ -616,7 +626,8 @@ func securePasswordUpdateKDF(password: String, derivation: TwoStepSecurePassword var nextSalt = salt var randomSalt = Data() randomSalt.count = 32 - randomSalt.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + randomSalt.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) arc4random_buf(bytes, 32) } nextSalt.append(randomSalt) @@ -630,7 +641,8 @@ func securePasswordUpdateKDF(password: String, derivation: TwoStepSecurePassword var nextSalt = salt var randomSalt = Data() randomSalt.count = 32 - randomSalt.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + randomSalt.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) arc4random_buf(bytes, 32) } nextSalt.append(randomSalt) @@ -746,7 +758,8 @@ private func masterNotificationsKey(masterNotificationKeyValue: Atomic) -> Bool in + if !secretData.withUnsafeMutableBytes({ rawBytes -> Bool in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) let copyResult = SecRandomCopyBytes(nil, secretDataCount, bytes) return copyResult == errSecSuccess }) { @@ -785,7 +798,8 @@ public func decryptedNotificationPayload(key: MasterNotificationKey, data: Data) } var dataLength: Int32 = 0 - data.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + data.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) memcpy(&dataLength, bytes, 4) } @@ -1087,7 +1101,7 @@ public class Account { })) self.managedOperationsDisposable.add((accountManager.sharedData(keys: [SharedDataKeys.proxySettings]) |> map { sharedData -> ProxyServerSettings? in - if let settings = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings { + if let settings = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) { return settings.effectiveActiveServer } else { return nil @@ -1138,7 +1152,7 @@ public class Account { guard let mediaBox = mediaBox else { return } - let settings: CacheStorageSettings = sharedData.entries[SharedDataKeys.cacheStorageSettings] as? CacheStorageSettings ?? CacheStorageSettings.defaultSettings + let settings: CacheStorageSettings = sharedData.entries[SharedDataKeys.cacheStorageSettings]?.get(CacheStorageSettings.self) ?? CacheStorageSettings.defaultSettings mediaBox.setMaxStoreTimes(general: settings.defaultCacheStorageTimeout, shortLived: 60 * 60, gigabytesLimit: settings.defaultCacheStorageLimitGigabytes) }) } @@ -1238,9 +1252,9 @@ public class Account { } public func addUpdates(serializedData: Data) -> Void { - if let object = Api.parse(Buffer(data: serializedData)) { - //self.stateManager.addUpdates() - } + /*if let object = Api.parse(Buffer(data: serializedData)) { + self.stateManager.addUpdates() + }*/ } } diff --git a/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift b/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift index 194cf5a28c..99c1264e63 100644 --- a/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift +++ b/submodules/TelegramCore/Sources/Account/AccountIntermediateState.swift @@ -591,7 +591,7 @@ struct AccountMutableState { self.readInboxMaxIds[peerId] = MessageId(peerId: peerId, namespace: namespace, id: maxIncomingReadId) } } - case let .ResetMessageTagSummary(peerId, namespace, count, range): + case .ResetMessageTagSummary: break } diff --git a/submodules/TelegramCore/Sources/Account/AccountManager.swift b/submodules/TelegramCore/Sources/Account/AccountManager.swift index 815540377f..52b68a2775 100644 --- a/submodules/TelegramCore/Sources/Account/AccountManager.swift +++ b/submodules/TelegramCore/Sources/Account/AccountManager.swift @@ -189,7 +189,7 @@ private var declaredEncodables: Void = { declareEncodable(CachedRecentPeers.self, f: { CachedRecentPeers(decoder: $0) }) //declareEncodable(AppChangelogState.self, f: { AppChangelogState(decoder: $0) }) //declareEncodable(AppConfiguration.self, f: { AppConfiguration(decoder: $0) }) - declareEncodable(JSON.self, f: { JSON(decoder: $0) }) + //declareEncodable(JSON.self, f: { JSON(decoder: $0) }) //declareEncodable(SearchBotsConfiguration.self, f: { SearchBotsConfiguration(decoder: $0) }) //declareEncodable(AutodownloadSettings.self, f: { AutodownloadSettings(decoder: $0 )}) declareEncodable(TelegramMediaPoll.self, f: { TelegramMediaPoll(decoder: $0) }) diff --git a/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift b/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift index 6068ef3655..82c7ed5789 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/ReplyMarkupMessageAttribute.swift @@ -30,7 +30,7 @@ extension ReplyMarkupButton { case let .inputKeyboardButtonUrlAuth(_, text, fwdText, url, _): self.init(title: text, titleWhenForwarded: fwdText, action: .urlAuth(url: url, buttonId: 0)) case let .keyboardButtonRequestPoll(_, quiz, text): - var isQuiz: Bool? = quiz.flatMap { quiz in + let isQuiz: Bool? = quiz.flatMap { quiz in if case .boolTrue = quiz { return true } else { diff --git a/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift b/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift index 1e15edb319..9eb5c48031 100644 --- a/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift +++ b/submodules/TelegramCore/Sources/ApiUtils/StoreMessage_Telegram.swift @@ -116,8 +116,8 @@ public func tagsForStoreMessage(incoming: Bool, attributes: [MessageAttribute], func apiMessagePeerId(_ messsage: Api.Message) -> PeerId? { switch messsage { - case let .message(message): - let chatPeerId = message.peerId + case let .message(_, _, _, messagePeerId, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + let chatPeerId = messagePeerId return chatPeerId.peerId case let .messageEmpty(_, _, peerId): if let peerId = peerId { @@ -132,7 +132,7 @@ func apiMessagePeerId(_ messsage: Api.Message) -> PeerId? { func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { switch message { - case let .message(flags, _, fromId, chatPeerId, fwdHeader, viaBotId, _, _, _, media, _, entities, _, _, _, _, _, _, _, _): + case let .message(_, _, fromId, chatPeerId, fwdHeader, viaBotId, _, _, _, media, _, entities, _, _, _, _, _, _, _, _): let peerId: PeerId = chatPeerId.peerId var result = [peerId] @@ -145,11 +145,11 @@ func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { if let fwdHeader = fwdHeader { switch fwdHeader { - case let .messageFwdHeader(messageFwdHeader): - if let fromId = messageFwdHeader.fromId { + case let .messageFwdHeader(_, fromId, _, _, _, _, savedFromPeer, _, _): + if let fromId = fromId { result.append(fromId.peerId) } - if let savedFromPeer = messageFwdHeader.savedFromPeer { + if let savedFromPeer = savedFromPeer { result.append(savedFromPeer.peerId) } } diff --git a/submodules/TelegramCore/Sources/Authorization.swift b/submodules/TelegramCore/Sources/Authorization.swift index 17dde9f772..bccf7ce12d 100644 --- a/submodules/TelegramCore/Sources/Authorization.swift +++ b/submodules/TelegramCore/Sources/Authorization.swift @@ -227,8 +227,8 @@ public func authorizeWithCode(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .password(password): - return .single(.password(hint: password.hint ?? "")) + case let .password(_, _, _, _, hint, _, _, _, _, _): + return .single(.password(hint: hint ?? "")) } } case let (_, errorDescription): diff --git a/submodules/TelegramCore/Sources/Network/FetchedMediaResource.swift b/submodules/TelegramCore/Sources/Network/FetchedMediaResource.swift index 08bbca5c45..9c5b99c7a5 100644 --- a/submodules/TelegramCore/Sources/Network/FetchedMediaResource.swift +++ b/submodules/TelegramCore/Sources/Network/FetchedMediaResource.swift @@ -48,7 +48,7 @@ public func fetchedMediaResource(mediaBox: MediaBox, reference: MediaResourceRef } return combineLatest(signals) |> ignoreValues - |> map { _ -> FetchResourceSourceType in .local } + |> map { _ -> FetchResourceSourceType in } |> then(.single(.local)) } else { return mediaBox.fetchedResource(reference.resource, parameters: MediaResourceFetchParameters(tag: TelegramMediaResourceFetchTag(statsCategory: statsCategory), info: TelegramCloudMediaResourceFetchInfo(reference: reference, preferBackgroundReferenceRevalidation: preferBackgroundReferenceRevalidation, continueInBackground: continueInBackground), isRandomAccessAllowed: isRandomAccessAllowed), implNext: reportResultStatus) @@ -61,7 +61,7 @@ enum RevalidateMediaReferenceError { public func stickerPackFileReference(_ file: TelegramMediaFile) -> FileMediaReference { for attribute in file.attributes { - if case let .Sticker(sticker) = attribute, let stickerPack = sticker.packReference { + if case let .Sticker(_, packReferenceValue, _) = attribute, let stickerPack = packReferenceValue { return .stickerPack(stickerPack: stickerPack, media: file) } } @@ -292,8 +292,6 @@ final class MediaReferenceRevalidationContext { } else { error(.generic) } - }, error: { _ in - error(.generic) }) }) |> mapToSignal { next -> Signal in if let next = next as? Message { @@ -308,7 +306,6 @@ final class MediaReferenceRevalidationContext { return self.genericItem(key: .stickerPack(stickerPack: stickerPack), background: background, request: { next, error in return (updatedRemoteStickerPack(postbox: postbox, network: network, reference: stickerPack) |> mapError { _ -> RevalidateMediaReferenceError in - return .generic }).start(next: { value in if let value = value { next(value) @@ -331,7 +328,6 @@ final class MediaReferenceRevalidationContext { return self.genericItem(key: .webPage(webPage: webPage), background: background, request: { next, error in return (updatedRemoteWebpage(postbox: postbox, network: network, webPage: webPage) |> mapError { _ -> RevalidateMediaReferenceError in - return .generic }).start(next: { value in if let value = value { next(value) @@ -443,7 +439,6 @@ final class MediaReferenceRevalidationContext { return (telegramThemes(postbox: postbox, network: network, accountManager: nil, forceUpdate: true) |> take(1) |> mapError { _ -> RevalidateMediaReferenceError in - return .generic }).start(next: { value in next(value) }, error: { _ in @@ -462,7 +457,6 @@ final class MediaReferenceRevalidationContext { return self.genericItem(key: .peerAvatars(peer: peer), background: background, request: { next, error in return (_internal_requestPeerPhotos(postbox: postbox, network: network, peerId: peer.id) |> mapError { _ -> RevalidateMediaReferenceError in - return .generic }).start(next: { value in next(value) }, error: { _ in @@ -504,8 +498,8 @@ func revalidateMediaResourceReference(postbox: Postbox, network: Network, revali if revalidateWithStickerpack { var stickerPackReference: StickerPackReference? for attribute in file.attributes { - if case let .Sticker(sticker) = attribute { - if let packReference = sticker.packReference { + if case let .Sticker(_, packReferenceValue, _) = attribute { + if let packReference = packReferenceValue { stickerPackReference = packReference } } @@ -599,7 +593,7 @@ func revalidateMediaResourceReference(postbox: Postbox, network: Network, revali case let .standalone(media): if let file = media as? TelegramMediaFile { for attribute in file.attributes { - if case let .Sticker(sticker) = attribute, let stickerPack = sticker.packReference { + if case let .Sticker(_, packReferenceValue, _) = attribute, let stickerPack = packReferenceValue { return revalidationContext.stickerPack(postbox: postbox, network: network, background: info.preferBackgroundReferenceRevalidation, stickerPack: stickerPack) |> mapToSignal { result -> Signal in for item in result.1 { diff --git a/submodules/TelegramCore/Sources/Network/MultipartFetch.swift b/submodules/TelegramCore/Sources/Network/MultipartFetch.swift index 3d0ff61557..993fb735d7 100644 --- a/submodules/TelegramCore/Sources/Network/MultipartFetch.swift +++ b/submodules/TelegramCore/Sources/Network/MultipartFetch.swift @@ -32,8 +32,10 @@ private final class MultipartDownloadState { assert(decryptedData.count % 16 == 0) let decryptedDataCount = decryptedData.count assert(offset == Int(self.currentSize)) - decryptedData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in - self.aesIv.withUnsafeMutableBytes { (iv: UnsafeMutablePointer) -> Void in + decryptedData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + self.aesIv.withUnsafeMutableBytes { rawIv -> Void in + let iv = rawIv.baseAddress!.assumingMemoryBound(to: UInt8.self) MTAesDecryptBytesInplaceAndModifyIv(bytes, decryptedDataCount, self.aesKey, iv) } } @@ -507,7 +509,8 @@ private enum MultipartFetchSource { } else { var partIv = iv let partIvCount = partIv.count - partIv.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + partIv.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) var ivOffset: Int32 = (offset / 16).bigEndian memcpy(bytes.advanced(by: partIvCount - 4), &ivOffset, 4) } diff --git a/submodules/TelegramCore/Sources/Network/MultipartUpload.swift b/submodules/TelegramCore/Sources/Network/MultipartUpload.swift index 3a40dc91da..c4eba9f13e 100644 --- a/submodules/TelegramCore/Sources/Network/MultipartUpload.swift +++ b/submodules/TelegramCore/Sources/Network/MultipartUpload.swift @@ -17,7 +17,8 @@ private struct UploadPart { } private func md5(_ data: Data) -> Data { - return data.withUnsafeBytes { bytes -> Data in + return data.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress! return CryptoMD5(bytes, Int32(data.count)) } } @@ -54,11 +55,13 @@ private final class MultipartUploadState { encryptedData.count = encryptedData.count + paddingSize } let encryptedDataCount = encryptedData.count - encryptedData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + encryptedData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) if paddingSize != 0 { arc4random_buf(bytes.advanced(by: encryptedDataCount - paddingSize), paddingSize) } - self.aesIv.withUnsafeMutableBytes { (iv: UnsafeMutablePointer) -> Void in + self.aesIv.withUnsafeMutableBytes { rawIv -> Void in + let iv = rawIv.baseAddress!.assumingMemoryBound(to: UInt8.self) MTAesEncryptBytesInplaceAndModifyIv(bytes, encryptedDataCount, self.aesKey, iv) } } @@ -411,10 +414,12 @@ func multipartUpload(network: Network, postbox: Postbox, source: MultipartUpload aesKey.count = 32 var aesIv = Data() aesIv.count = 32 - aesKey.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + aesKey.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress! arc4random_buf(bytes, 32) } - aesIv.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + aesIv.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress! arc4random_buf(bytes, 32) } encryptionKey = SecretFileEncryptionKey(aesKey: aesKey, aesIv: aesIv) @@ -466,7 +471,9 @@ func multipartUpload(network: Network, postbox: Postbox, source: MultipartUpload if let encryptionKey = encryptionKey { let keyDigest = md5(encryptionKey.aesKey + encryptionKey.aesIv) var fingerprint: Int32 = 0 - keyDigest.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyDigest.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + withUnsafeMutableBytes(of: &fingerprint, { ptr -> Void in let uintPtr = ptr.baseAddress!.assumingMemoryBound(to: UInt8.self) uintPtr[0] = bytes[0] ^ bytes[4] diff --git a/submodules/TelegramCore/Sources/Network/Network.swift b/submodules/TelegramCore/Sources/Network/Network.swift index 00d91651f6..af638d717a 100644 --- a/submodules/TelegramCore/Sources/Network/Network.swift +++ b/submodules/TelegramCore/Sources/Network/Network.swift @@ -480,13 +480,10 @@ func initializedNetwork(accountId: AccountRecordId, arguments: NetworkInitializa let key = SharedContextStore.Key(accountId: accountId) let context: MTContext - if false, let current = store.contexts[key] { - context = current - context.updateApiEnvironment({ _ in return apiEnvironment}) - } else { - context = MTContext(serialization: serialization, encryptionProvider: arguments.encryptionProvider, apiEnvironment: apiEnvironment, isTestingEnvironment: testingEnvironment, useTempAuthKeys: useTempAuthKeys) - store.contexts[key] = context - } + + context = MTContext(serialization: serialization, encryptionProvider: arguments.encryptionProvider, apiEnvironment: apiEnvironment, isTestingEnvironment: testingEnvironment, useTempAuthKeys: useTempAuthKeys) + store.contexts[key] = context + contextValue = context } @@ -627,7 +624,7 @@ private final class NetworkHelper: NSObject, MTContextChangeListener { self.contextLoggedOutUpdated = contextLoggedOutUpdated } - func fetchContextDatacenterPublicKeys(_ context: MTContext!, datacenterId: Int) -> MTSignal! { + func fetchContextDatacenterPublicKeys(_ context: MTContext, datacenterId: Int) -> MTSignal { return MTSignal { subscriber in let disposable = self.requestPublicKeys(datacenterId).start(next: { next in subscriber?.putNext(next) @@ -640,7 +637,7 @@ private final class NetworkHelper: NSObject, MTContextChangeListener { } } - func isContextNetworkAccessAllowed(_ context: MTContext!) -> MTSignal! { + func isContextNetworkAccessAllowed(_ context: MTContext) -> MTSignal { return MTSignal { subscriber in let disposable = self.isContextNetworkAccessAllowedImpl().start(next: { next in subscriber?.putNext(next as NSNumber) @@ -653,12 +650,12 @@ private final class NetworkHelper: NSObject, MTContextChangeListener { } } - func contextApiEnvironmentUpdated(_ context: MTContext!, apiEnvironment: MTApiEnvironment!) { + func contextApiEnvironmentUpdated(_ context: MTContext, apiEnvironment: MTApiEnvironment) { let settings: MTSocksProxySettings? = apiEnvironment.socksProxySettings self.contextProxyIdUpdated(settings.flatMap(NetworkContextProxyId.init(settings:))) } - func contextLoggedOut(_ context: MTContext!) { + func contextLoggedOut(_ context: MTContext) { self.contextLoggedOutUpdated() } } diff --git a/submodules/TelegramCore/Sources/PeerStatistics.swift b/submodules/TelegramCore/Sources/PeerStatistics.swift index adb54cbb4a..97e85702a1 100644 --- a/submodules/TelegramCore/Sources/PeerStatistics.swift +++ b/submodules/TelegramCore/Sources/PeerStatistics.swift @@ -1090,9 +1090,8 @@ extension GroupStatsTopInviter { extension GroupStats { convenience init(apiMegagroupStats: Api.stats.MegagroupStats) { switch apiMegagroupStats { - case let .megagroupStats(period, members, messages, viewers, posters, apiGrowthGraph, apiMembersGraph, apiNewMembersBySourceGraph, apiLanguagesGraph, apiMessagesGraph, apiActionsGraph, apiTopHoursGraph, apiTopWeekdaysGraph, topPosters, topAdmins, topInviters, users): + case let .megagroupStats(period, members, messages, viewers, posters, apiGrowthGraph, apiMembersGraph, apiNewMembersBySourceGraph, apiLanguagesGraph, apiMessagesGraph, apiActionsGraph, apiTopHoursGraph, apiTopWeekdaysGraph, topPosters, topAdmins, topInviters, _): let growthGraph = StatsGraph(apiStatsGraph: apiGrowthGraph) - let isEmpty = growthGraph.isEmpty self.init(period: StatsDateRange(apiStatsDateRangeDays: period), members: StatsValue(apiStatsAbsValueAndPrev: members), messages: StatsValue(apiStatsAbsValueAndPrev: messages), viewers: StatsValue(apiStatsAbsValueAndPrev: viewers), posters: StatsValue(apiStatsAbsValueAndPrev: posters), growthGraph: growthGraph, membersGraph: StatsGraph(apiStatsGraph: apiMembersGraph), newMembersBySourceGraph: StatsGraph(apiStatsGraph: apiNewMembersBySourceGraph), languagesGraph: StatsGraph(apiStatsGraph: apiLanguagesGraph), messagesGraph: StatsGraph(apiStatsGraph: apiMessagesGraph), actionsGraph: StatsGraph(apiStatsGraph: apiActionsGraph), topHoursGraph: StatsGraph(apiStatsGraph: apiTopHoursGraph), topWeekdaysGraph: StatsGraph(apiStatsGraph: apiTopWeekdaysGraph), topPosters: topPosters.map { GroupStatsTopPoster(apiStatsGroupTopPoster: $0) }, topAdmins: topAdmins.map { GroupStatsTopAdmin(apiStatsGroupTopAdmin: $0) }, topInviters: topInviters.map { GroupStatsTopInviter(apiStatsGroupTopInviter: $0) }) } diff --git a/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift index 28f62f891c..aa6f2933ba 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/EnqueueMessage.swift @@ -345,7 +345,7 @@ func enqueueMessages(transaction: Transaction, account: Account, peerId: PeerId, globallyUniqueIds.append(randomId) switch message { - case let .message(text, requestedAttributes, mediaReference, replyToMessageId, localGroupingKey, correlationId): + case let .message(text, requestedAttributes, mediaReference, replyToMessageId, localGroupingKey, _): var peerAutoremoveTimeout: Int32? if let peer = peer as? TelegramSecretChat { var isAction = false @@ -517,7 +517,7 @@ func enqueueMessages(transaction: Transaction, account: Account, peerId: PeerId, } storeMessages.append(StoreMessage(peerId: peerId, namespace: messageNamespace, globallyUniqueId: randomId, groupingKey: localGroupingKey, threadId: threadId, timestamp: effectiveTimestamp, flags: flags, tags: tags, globalTags: globalTags, localTags: localTags, forwardInfo: nil, authorId: authorId, text: text, attributes: attributes, media: mediaList)) - case let .forward(source, grouping, requestedAttributes, correlationId): + case let .forward(source, grouping, requestedAttributes, _): let sourceMessage = transaction.getMessage(source) if let sourceMessage = sourceMessage, let author = sourceMessage.author ?? sourceMessage.peers[sourceMessage.id.peerId] { var messageText = sourceMessage.text diff --git a/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift b/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift index e1b71406a3..61cdf3b326 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/PendingMessageUploadedContent.swift @@ -107,8 +107,8 @@ func mediaContentToUpload(network: Network, postbox: Postbox, auxiliaryMethods: if let resource = file.resource as? CloudDocumentMediaResource { if peerId.namespace == Namespaces.Peer.SecretChat { for attribute in file.attributes { - if case let .Sticker(sticker) = attribute { - if let _ = sticker.packReference { + if case let .Sticker(_, packReferenceValue, _) = attribute { + if let _ = packReferenceValue { return .single(.content(PendingMessageUploadedContentAndReuploadInfo(content: PendingMessageUploadedContent.text(text), reuploadInfo: nil))) } } @@ -234,7 +234,9 @@ private func maybePredownloadedImageResource(postbox: Postbox, peerId: PeerId, r if data.complete { if data.size < 5 * 1024 * 1024, let fileData = try? Data(contentsOf: URL(fileURLWithPath: data.path), options: .mappedRead) { let md5 = IncrementalMD5() - fileData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + fileData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + var offset = 0 let bufferSize = 32 * 1024 @@ -252,7 +254,7 @@ private func maybePredownloadedImageResource(postbox: Postbox, peerId: PeerId, r subscriber.putNext(.single(.localReference(reference))) } else { subscriber.putNext(cachedSentMediaReference(postbox: postbox, key: reference) - |> mapError { _ -> PendingMessageUploadError in return .generic } |> map { media -> PredownloadedResource in + |> mapError { _ -> PendingMessageUploadError in } |> map { media -> PredownloadedResource in if let media = media { return .media(media) } else { @@ -302,7 +304,7 @@ private func maybePredownloadedFileResource(postbox: Postbox, auxiliaryMethods: return .single(.localReference(nil)) } } - |> mapError { _ -> PendingMessageUploadError in return .generic } + |> mapError { _ -> PendingMessageUploadError in } } private func maybeCacheUploadedResource(postbox: Postbox, key: CachedSentMediaReferenceKey?, result: PendingMessageUploadedContentResult, media: Media) -> Signal { @@ -310,7 +312,7 @@ private func maybeCacheUploadedResource(postbox: Postbox, key: CachedSentMediaRe return postbox.transaction { transaction -> PendingMessageUploadedContentResult in storeCachedSentMediaReference(transaction: transaction, key: key, media: media) return result - } |> mapError { _ -> PendingMessageUploadError in return .generic } + } |> mapError { _ -> PendingMessageUploadError in } } else { return .single(result) } @@ -391,7 +393,6 @@ private func uploadedMediaImageContent(network: Network, postbox: Postbox, trans return transform |> mapError { _ -> PendingMessageUploadError in - return .generic } |> mapToSignal { transformResult -> Signal in switch transformResult { @@ -440,7 +441,7 @@ private func uploadedMediaImageContent(network: Network, postbox: Postbox, trans return postbox.transaction { transaction -> Api.InputPeer? in return transaction.getPeer(peerId).flatMap(apiInputPeer) } - |> mapError { _ -> PendingMessageUploadError in return .generic } + |> mapError { _ -> PendingMessageUploadError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { if autoclearMessageAttribute != nil { @@ -774,7 +775,7 @@ private func uploadedMediaFileContent(network: Network, postbox: Postbox, auxili return postbox.transaction { transaction -> Api.InputPeer? in return transaction.getPeer(peerId).flatMap(apiInputPeer) } - |> mapError { _ -> PendingMessageUploadError in return .generic } + |> mapError { _ -> PendingMessageUploadError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { return network.request(Api.functions.messages.uploadMedia(peer: inputPeer, media: .inputMediaUploadedDocument(flags: flags, file: inputFile, thumb: thumbnailFile, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: stickers, ttlSeconds: ttlSeconds))) diff --git a/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift index d567df6d1f..155e3ef164 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/RequestEditMessage.swift @@ -80,7 +80,7 @@ private func requestEditMessageInternal(postbox: Postbox, network: Network, stat } } return uploadedMedia - |> mapError { _ -> RequestEditMessageInternalError in return .error(.generic) } + |> mapError { _ -> RequestEditMessageInternalError in } |> mapToSignal { uploadedMediaResult -> Signal in var pendingMediaContent: PendingMessageUploadedContent? if let uploadedMediaResult = uploadedMediaResult { @@ -122,7 +122,7 @@ private func requestEditMessageInternal(postbox: Postbox, network: Network, stat } return (transaction.getPeer(messageId.peerId), message, peers) } - |> mapError { _ -> RequestEditMessageInternalError in return .error(.generic) } + |> mapError { _ -> RequestEditMessageInternalError in } |> mapToSignal { peer, message, associatedPeers -> Signal in if let peer = peer, let message = message, let inputPeer = apiInputPeer(peer) { var flags: Int32 = 1 << 11 @@ -241,7 +241,6 @@ private func requestEditMessageInternal(postbox: Postbox, network: Network, stat return .done(true) } |> mapError { _ -> RequestEditMessageInternalError in - return .error(.generic) } } else { return .single(.done(false)) diff --git a/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift b/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift index 1651211765..21f2c86f31 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/StandaloneSendMessage.swift @@ -62,7 +62,7 @@ public func standaloneSendMessage(account: Account, peerId: PeerId, text: String return .single(progress) case let .result(result): let sendContent = sendMessageContent(account: account, peerId: peerId, attributes: attributes, content: result) |> map({ _ -> Float in return 1.0 }) - return .single(1.0) |> then(sendContent |> mapError { _ -> StandaloneSendMessageError in return .generic }) + return .single(1.0) |> then(sendContent |> mapError { _ -> StandaloneSendMessageError in }) } } @@ -128,7 +128,6 @@ private func sendMessageContent(account: Account, peerId: PeerId, attributes: [M return .complete() } |> `catch` { _ -> Signal in - return .complete() } } else { return .complete() diff --git a/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift b/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift index d5c485279c..f05dfd4f19 100644 --- a/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift +++ b/submodules/TelegramCore/Sources/PendingMessages/StandaloneUploadedMedia.swift @@ -61,7 +61,7 @@ public func standaloneUploadedImage(account: Account, peerId: PeerId, text: Stri return account.postbox.transaction { transaction -> Api.InputPeer? in return transaction.getPeer(peerId).flatMap(apiInputPeer) } - |> mapError { _ -> StandaloneUploadMediaError in return .generic } + |> mapError { _ -> StandaloneUploadMediaError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { return account.network.request(Api.functions.messages.uploadMedia(peer: inputPeer, media: Api.InputMedia.inputMediaUploadedPhoto(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil))) @@ -150,7 +150,7 @@ public func standaloneUploadedFile(account: Account, peerId: PeerId, text: Strin return account.postbox.transaction { transaction -> Api.InputPeer? in return transaction.getPeer(peerId).flatMap(apiInputPeer) } - |> mapError { _ -> StandaloneUploadMediaError in return .generic } + |> mapError { _ -> StandaloneUploadMediaError in } |> mapToSignal { inputPeer -> Signal in if let inputPeer = inputPeer { var flags: Int32 = 0 diff --git a/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryption.swift b/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryption.swift index 376bca7183..90b410ebff 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryption.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SecretChatEncryption.swift @@ -10,7 +10,9 @@ private func messageKey(key: SecretChatKey, msgKey: UnsafeRawPointer, mode: Secr var sha1AData = Data() sha1AData.count = 16 + 32 - sha1AData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + sha1AData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes, msgKey, 16) memcpy(bytes.advanced(by: 16), key.key.memory.advanced(by: x), 32) } @@ -18,7 +20,9 @@ private func messageKey(key: SecretChatKey, msgKey: UnsafeRawPointer, mode: Secr var sha1BData = Data() sha1BData.count = 16 + 16 + 16 - sha1BData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + sha1BData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes, key.key.memory.advanced(by: 32 + x), 16) memcpy(bytes.advanced(by: 16), msgKey, 16) memcpy(bytes.advanced(by: 16 + 16), key.key.memory.advanced(by: 48 + x), 16) @@ -27,7 +31,9 @@ private func messageKey(key: SecretChatKey, msgKey: UnsafeRawPointer, mode: Secr var sha1CData = Data() sha1CData.count = 32 + 16 - sha1CData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + sha1CData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes, key.key.memory.advanced(by: 64 + x), 32) memcpy(bytes.advanced(by: 32), msgKey, 16) } @@ -35,7 +41,9 @@ private func messageKey(key: SecretChatKey, msgKey: UnsafeRawPointer, mode: Secr var sha1DData = Data() sha1DData.count = 16 + 32 - sha1DData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + sha1DData.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes, msgKey, 16) memcpy(bytes.advanced(by: 16), key.key.memory.advanced(by: 96 + x), 32) } @@ -43,32 +51,36 @@ private func messageKey(key: SecretChatKey, msgKey: UnsafeRawPointer, mode: Secr var aesKey = Data() aesKey.count = 8 + 12 + 12 - aesKey.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in - sha1A.withUnsafeBytes { (sha1A: UnsafePointer) -> Void in - memcpy(bytes, sha1A, 8) + aesKey.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + + sha1A.withUnsafeBytes { sha1A -> Void in + memcpy(bytes, sha1A.baseAddress!.assumingMemoryBound(to: UInt8.self), 8) } - sha1B.withUnsafeBytes { (sha1B: UnsafePointer) -> Void in - memcpy(bytes.advanced(by: 8), sha1B.advanced(by: 8), 12) + sha1B.withUnsafeBytes { sha1B -> Void in + memcpy(bytes.advanced(by: 8), sha1B.baseAddress!.assumingMemoryBound(to: UInt8.self).advanced(by: 8), 12) } - sha1C.withUnsafeBytes { (sha1C: UnsafePointer) -> Void in - memcpy(bytes.advanced(by: 8 + 12), sha1C.advanced(by: 4), 12) + sha1C.withUnsafeBytes { sha1C -> Void in + memcpy(bytes.advanced(by: 8 + 12), sha1C.baseAddress!.assumingMemoryBound(to: UInt8.self).advanced(by: 4), 12) } } var aesIv = Data() aesIv.count = 12 + 8 + 4 + 8 - aesIv.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in - sha1A.withUnsafeBytes { (sha1A: UnsafePointer) -> Void in - memcpy(bytes, sha1A.advanced(by: 8), 12) + aesIv.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + + sha1A.withUnsafeBytes { sha1A -> Void in + memcpy(bytes, sha1A.baseAddress!.assumingMemoryBound(to: UInt8.self).advanced(by: 8), 12) } - sha1B.withUnsafeBytes { (sha1B: UnsafePointer) -> Void in - memcpy(bytes.advanced(by: 12), sha1B, 8) + sha1B.withUnsafeBytes { sha1B -> Void in + memcpy(bytes.advanced(by: 12), sha1B.baseAddress!.assumingMemoryBound(to: UInt8.self), 8) } - sha1C.withUnsafeBytes { (sha1C: UnsafePointer) -> Void in - memcpy(bytes.advanced(by: 12 + 8), sha1C.advanced(by: 16), 4) + sha1C.withUnsafeBytes { sha1C -> Void in + memcpy(bytes.advanced(by: 12 + 8), sha1C.baseAddress!.assumingMemoryBound(to: UInt8.self).advanced(by: 16), 4) } - sha1D.withUnsafeBytes { (sha1D: UnsafePointer) -> Void in - memcpy(bytes.advanced(by: 12 + 8 + 4), sha1D, 8) + sha1D.withUnsafeBytes { sha1D -> Void in + memcpy(bytes.advanced(by: 12 + 8 + 4), sha1D.baseAddress!.assumingMemoryBound(to: UInt8.self), 8) } } return (aesKey, aesIv) @@ -127,7 +139,9 @@ func withDecryptedMessageContents(parameters: SecretChatEncryptionParameters, da } var payloadLength: Int32 = 0 - decryptedData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + decryptedData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(&payloadLength, bytes, 4) } @@ -137,7 +151,9 @@ func withDecryptedMessageContents(parameters: SecretChatEncryptionParameters, da } let calculatedMsgKeyData = MTSubdataSha1(decryptedData, 0, UInt(payloadLength) + 4) - let msgKeyMatches = calculatedMsgKeyData.withUnsafeBytes { (bytes: UnsafePointer) -> Bool in + let msgKeyMatches = calculatedMsgKeyData.withUnsafeBytes { rawBytes -> Bool in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return memcmp(bytes.advanced(by: calculatedMsgKeyData.count - 16), msgKey, 16) == 0 } @@ -145,7 +161,9 @@ func withDecryptedMessageContents(parameters: SecretChatEncryptionParameters, da return nil } - let result = decryptedData.withUnsafeBytes { (bytes: UnsafePointer) -> Data in + let result = decryptedData.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return Data(bytes: bytes.advanced(by: 4), count: Int(payloadLength)) } return MemoryBuffer(data: result) @@ -166,7 +184,9 @@ func withDecryptedMessageContents(parameters: SecretChatEncryptionParameters, da } var payloadLength: Int32 = 0 - decryptedData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + decryptedData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(&payloadLength, bytes, 4) } @@ -203,7 +223,9 @@ func withDecryptedMessageContents(parameters: SecretChatEncryptionParameters, da return nil } - let result = decryptedData.withUnsafeBytes { (bytes: UnsafePointer) -> Data in + let result = decryptedData.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return Data(bytes: bytes.advanced(by: 4), count: Int(payloadLength)) } return MemoryBuffer(data: result) @@ -233,7 +255,7 @@ func encryptedMessageContents(parameters: SecretChatEncryptionParameters, data: var msgKey = MTSha1(payloadData) msgKey.replaceSubrange(0 ..< (msgKey.count - 16), with: Data()) - var randomBuf = malloc(16)! + let randomBuf = malloc(16)! defer { free(randomBuf) } @@ -246,7 +268,9 @@ func encryptedMessageContents(parameters: SecretChatEncryptionParameters, data: randomIndex += 1 } - let (aesKey, aesIv) = msgKey.withUnsafeBytes { (bytes: UnsafePointer) -> (Data, Data) in + let (aesKey, aesIv) = msgKey.withUnsafeBytes { rawBytes -> (Data, Data) in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return messageKey(key: parameters.key, msgKey: bytes, mode: parameters.mode) } @@ -262,7 +286,9 @@ func encryptedMessageContents(parameters: SecretChatEncryptionParameters, data: case let .v2(role): var randomBytes = Data(count: 128) let randomBytesCount = randomBytes.count - randomBytes.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + randomBytes.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + arc4random_buf(bytes, randomBytesCount) } @@ -305,7 +331,9 @@ func encryptedMessageContents(parameters: SecretChatEncryptionParameters, data: let msgKey = keyLarge.subdata(in: 8 ..< (8 + 16)) - let (aesKey, aesIv) = msgKey.withUnsafeBytes { (bytes: UnsafePointer) -> (Data, Data) in + let (aesKey, aesIv) = msgKey.withUnsafeBytes { rawBytes -> (Data, Data) in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + return messageKey(key: parameters.key, msgKey: bytes, mode: parameters.mode) } diff --git a/submodules/TelegramCore/Sources/SecretChats/SecretChatRekeySession.swift b/submodules/TelegramCore/Sources/SecretChats/SecretChatRekeySession.swift index 2230accf37..095406d421 100644 --- a/submodules/TelegramCore/Sources/SecretChats/SecretChatRekeySession.swift +++ b/submodules/TelegramCore/Sources/SecretChats/SecretChatRekeySession.swift @@ -41,7 +41,7 @@ func secretChatAdvanceRekeySessionIfNeeded(encryptionProvider: EncryptionProvide if let rekeySession = sequenceState.rekeyState, rekeySession.id == rekeySessionId { switch rekeySession.data { case let .requested(a, config): - var gValue: Int32 = config.g.byteSwapped + //var gValue: Int32 = config.g.byteSwapped let p = config.p.makeData() let aData = a.makeData() @@ -62,7 +62,9 @@ func secretChatAdvanceRekeySessionIfNeeded(encryptionProvider: EncryptionProvide let keyHash = MTSha1(key) var keyFingerprint: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } diff --git a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift index 759ee4495d..6e44cf5760 100644 --- a/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift +++ b/submodules/TelegramCore/Sources/SecretChats/UpdateSecretChat.swift @@ -14,10 +14,10 @@ struct SecretChatRequestData { func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: PeerId, transaction: Transaction, mediaBox: MediaBox, chat: Api.EncryptedChat, requestData: SecretChatRequestData?) { let currentPeer = transaction.getPeer(chat.peerId) as? TelegramSecretChat let currentState = transaction.getPeerChatState(chat.peerId) as? SecretChatState - let settings = transaction.getPreferencesEntry(key: PreferencesKeys.secretChatSettings) as? SecretChatSettings ?? SecretChatSettings.defaultSettings + let settings = transaction.getPreferencesEntry(key: PreferencesKeys.secretChatSettings)?.get(SecretChatSettings.self) ?? SecretChatSettings.defaultSettings assert((currentPeer == nil) == (currentState == nil)) switch chat { - case let .encryptedChat(_, _, _, adminId, _, gAOrB, remoteKeyFingerprint): + case let .encryptedChat(_, _, _, adminId, _, gAOrB, _): if let currentPeer = currentPeer, let currentState = currentState, adminId == accountPeerId.id._internalGetInt64Value() { if case let .handshake(handshakeState) = currentState.embeddedState, case let .requested(_, p, a) = handshakeState { let pData = p.makeData() @@ -43,7 +43,9 @@ func updateSecretChat(encryptionProvider: EncryptionProvider, accountPeerId: Pee let keyHash = MTSha1(key) var keyFingerprint: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } diff --git a/submodules/TelegramCore/Sources/Settings/ContentSettings.swift b/submodules/TelegramCore/Sources/Settings/ContentSettings.swift index ba16ddabe3..b3b0b9d160 100644 --- a/submodules/TelegramCore/Sources/Settings/ContentSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/ContentSettings.swift @@ -24,14 +24,14 @@ private extension ContentSettings { } public func getContentSettings(transaction: Transaction) -> ContentSettings { - let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration) as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue return ContentSettings(appConfiguration: appConfiguration) } public func getContentSettings(postbox: Postbox) -> Signal { return postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { view -> ContentSettings in - let appConfiguration: AppConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue return ContentSettings(appConfiguration: appConfiguration) } |> distinctUntilChanged diff --git a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift index 0cff5f6b0a..3837d876e2 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift @@ -215,12 +215,12 @@ private func activeChannelsFromDifference(_ difference: Api.updates.Difference) var chats: [Api.Chat] = [] switch difference { - case let .difference(difference): - chats = difference.chats + case let .difference(_, _, _, differenceChats, _, _): + chats = differenceChats case .differenceEmpty: break - case let .differenceSlice(differenceSlice): - chats = differenceSlice.chats + case let .differenceSlice(_, _, _, differenceChats, _, _): + chats = differenceChats case .differenceTooLong: break } @@ -466,7 +466,7 @@ private func initialStateWithPeerIds(_ transaction: Transaction, peerIds: Set [Api.Update] { rhsPts = pts case let .updateEditChannelMessage(_, pts, _): rhsPts = pts - case let .updatePinnedChannelMessages(_, channelId, _, pts, _): + case let .updatePinnedChannelMessages(_, _, _, pts, _): rhsPts = pts default: break @@ -1190,7 +1190,7 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo }) case let .updateUserStatus(userId, status): updatedState.mergePeerPresences([PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)): status], explicit: true) - case let .updateUserName(userId, firstName, lastName, username): + case let .updateUserName(userId, _, _, username): //TODO add contact checking for apply first and last name updatedState.updatePeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)), { peer in if let user = peer as? TelegramUser { @@ -1375,8 +1375,8 @@ private func finalStateWithUpdatesAndServerTime(postbox: Postbox, network: Netwo case let .updateLangPack(difference): let langCode: String switch difference { - case let .langPackDifference(langPackDifference): - langCode = langPackDifference.langCode + case let .langPackDifference(langCodeValue, _, _, _): + langCode = langCodeValue } updatedState.updateLangPack(langCode: langCode, difference: difference) case let .updateMessagePoll(_, pollId, poll, results): @@ -1521,6 +1521,7 @@ private func resolveAssociatedMessages(network: Network, state: AccountMutableSt return .single(state) } else { var missingPeers = false + let _ = missingPeers var signals: [Signal<([Api.Message], [Api.Chat], [Api.User]), NoError>] = [] for (peerId, messageIds) in messagesIdsGroupedByPeerId(missingMessageIds) { @@ -2027,7 +2028,7 @@ private func pollChannel(network: Network, peer: Peer, state: AccountMutableStat apiTimeout = timeout let channelPts: Int32 - if let previousState = updatedState.channelStates[peer.id] { + if let _ = updatedState.channelStates[peer.id] { channelPts = pts } else { channelPts = pts @@ -2039,7 +2040,7 @@ private func pollChannel(network: Network, peer: Peer, state: AccountMutableStat var parameters: (peer: Api.Peer, pts: Int32, topMessage: Int32, readInboxMaxId: Int32, readOutboxMaxId: Int32, unreadCount: Int32, unreadMentionsCount: Int32)? switch dialog { - case let .dialog(_, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, notifySettings, pts, draft, folderId): + case let .dialog(_, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, _, pts, _, _): if let pts = pts { parameters = (peer, pts, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount) } @@ -2592,8 +2593,8 @@ func replayFinalState(accountManager: AccountManager take(1) |> mapToSignal { [weak self] state -> Signal<(difference: Api.updates.Difference?, finalStatte: AccountReplayedFinalState?, skipBecauseOfError: Bool), NoError> in if let authorizedState = state.state { - var flags: Int32 = 0 - var ptsTotalLimit: Int32? = nil + let flags: Int32 = 0 + let ptsTotalLimit: Int32? = nil #if DEBUG //flags = 1 << 0 //ptsTotalLimit = 1000 @@ -533,9 +533,6 @@ public final class AccountStateManager { assertionFailure() } } - }, error: { _ in - assertionFailure() - Logger.shared.log("AccountStateManager", "processUpdateGroups signal completed with error") }) case let .collectUpdateGroups(_, timeout): self.operationTimer?.invalidate() @@ -634,9 +631,7 @@ public final class AccountStateManager { } } } - let _ = (signal |> deliverOn(self.queue)).start(error: { _ in - completed() - }, completed: { + let _ = (signal |> deliverOn(self.queue)).start(completed: { completed() }) case let .processEvents(operationId, events): @@ -737,8 +732,6 @@ public final class AccountStateManager { if let strongSelf = self { strongSelf.notificationMessagesPipe.putNext(messages) } - }, error: { _ in - completed() }, completed: { completed() }) @@ -833,10 +826,6 @@ public final class AccountStateManager { } completion() } - }, error: { _ in - assertionFailure() - Logger.shared.log("AccountStateManager", "processUpdateGroups signal completed with error") - completion() }) } } @@ -1053,7 +1042,7 @@ public final class AccountStateManager { if let updates = Api.parse(Buffer(data: rawData)) as? Api.Updates { switch updates { - case let .updates(updates, users, chats, date, seq): + case let .updates(updates, _, _, _, _): for update in updates { switch update { case let .updatePhoneCall(phoneCall): @@ -1122,7 +1111,7 @@ public func messagesForNotification(transaction: Transaction, id: MessageId, alw if let notificationSettings = transaction.getPeerNotificationSettings(notificationPeerId) as? TelegramPeerNotificationSettings { var defaultSound: PeerMessageSound = .bundledModern(id: 0) var defaultNotify: Bool = true - if let globalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications) as? GlobalNotificationSettings { + if let globalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) { if id.peerId.namespace == Namespaces.Peer.CloudUser { defaultNotify = globalNotificationSettings.effective.privateChats.enabled defaultSound = globalNotificationSettings.effective.privateChats.sound diff --git a/submodules/TelegramCore/Sources/State/AccountViewTracker.swift b/submodules/TelegramCore/Sources/State/AccountViewTracker.swift index 992161c9c6..db38aa4c90 100644 --- a/submodules/TelegramCore/Sources/State/AccountViewTracker.swift +++ b/submodules/TelegramCore/Sources/State/AccountViewTracker.swift @@ -1172,7 +1172,7 @@ public final class AccountViewTracker { return ids } - |> deliverOn(self.queue)).start(next: { [weak self] messageIds in + |> deliverOn(self.queue)).start(next: { _ in //self?.updateMarkMentionsSeenForMessageIds(messageIds: messageIds) }) } @@ -1585,8 +1585,6 @@ public final class AccountViewTracker { } else { subscriber.putNext([]) } - }, error: { error in - subscriber.putError(error) }, completed: { subscriber.putCompletion() }) @@ -1721,7 +1719,7 @@ public final class AccountViewTracker { var currentMessages: [Message] = [] for entry in view.entries { switch entry { - case let .hole(index): + case .hole: if !currentMessages.isEmpty { entries.append(.message(currentMessages[currentMessages.count - 1], currentMessages)) currentMessages.removeAll() diff --git a/submodules/TelegramCore/Sources/State/AppChangelog.swift b/submodules/TelegramCore/Sources/State/AppChangelog.swift index 502a510c7f..49049f1db1 100644 --- a/submodules/TelegramCore/Sources/State/AppChangelog.swift +++ b/submodules/TelegramCore/Sources/State/AppChangelog.swift @@ -10,7 +10,7 @@ func managedAppChangelog(postbox: Postbox, network: Network, stateManager: Accou |> take(1) |> mapToSignal { _ -> Signal in return postbox.transaction { transaction -> AppChangelogState in - return transaction.getPreferencesEntry(key: PreferencesKeys.appChangelogState) as? AppChangelogState ?? AppChangelogState.default + return transaction.getPreferencesEntry(key: PreferencesKeys.appChangelogState)?.get(AppChangelogState.self) ?? AppChangelogState.default } |> mapToSignal { appChangelogState -> Signal in let appChangelogState = appChangelogState diff --git a/submodules/TelegramCore/Sources/State/AppChangelogState.swift b/submodules/TelegramCore/Sources/State/AppChangelogState.swift index ce6cd6da98..85858cd126 100644 --- a/submodules/TelegramCore/Sources/State/AppChangelogState.swift +++ b/submodules/TelegramCore/Sources/State/AppChangelogState.swift @@ -6,6 +6,6 @@ import MtProtoKit func updateAppChangelogState(transaction: Transaction, _ f: @escaping (AppChangelogState) -> AppChangelogState) { transaction.updatePreferencesEntry(key: PreferencesKeys.appChangelogState, { current in - return PreferencesEntry(f((current as? AppChangelogState) ?? AppChangelogState.default)) + return PreferencesEntry(f((current?.get(AppChangelogState.self)) ?? AppChangelogState.default)) }) } diff --git a/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift b/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift index 57de860b2e..8fed6be810 100644 --- a/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift +++ b/submodules/TelegramCore/Sources/State/ApplyUpdateMessage.swift @@ -64,12 +64,12 @@ func applyUpdateMessage(postbox: Postbox, stateManager: AccountStateManager, mes var updatedTimestamp: Int32? if let apiMessage = apiMessage { switch apiMessage { - case let .message(message): - updatedTimestamp = message.date + case let .message(_, _, _, _, _, _, _, date, _, _, _, _, _, _, _, _, _, _, _, _): + updatedTimestamp = date case .messageEmpty: break - case let .messageService(messageService): - updatedTimestamp = messageService.date + case let .messageService(_, _, _, _, _, date, _, _): + updatedTimestamp = date } } else { switch result { diff --git a/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift b/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift index 4f112c6fd5..d7af4e5d03 100644 --- a/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift +++ b/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift @@ -14,14 +14,16 @@ enum CachedSentMediaReferenceKey { case let .image(hash): let result = ValueBoxKey(length: 1 + hash.count) result.setUInt8(0, value: 0) - hash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + hash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) memcpy(result.memory.advanced(by: 1), bytes, hash.count) } return result case let .file(hash): let result = ValueBoxKey(length: 1 + hash.count) result.setUInt8(0, value: 1) - hash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + hash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) memcpy(result.memory.advanced(by: 1), bytes, hash.count) } return result diff --git a/submodules/TelegramCore/Sources/State/CallSessionManager.swift b/submodules/TelegramCore/Sources/State/CallSessionManager.swift index 82ed3e0ab0..65ad4a5c5d 100644 --- a/submodules/TelegramCore/Sources/State/CallSessionManager.swift +++ b/submodules/TelegramCore/Sources/State/CallSessionManager.swift @@ -562,7 +562,7 @@ private final class CallSessionManagerContext { |> timeout(5.0, queue: strongSelf.queue, alternate: .single(nil)) |> deliverOnMainQueue).start(next: { debugLog in if let debugLog = debugLog { - _internal_saveCallDebugLog(network: network, callId: CallId(id: id, accessHash: accessHash), log: debugLog).start() + let _ = _internal_saveCallDebugLog(network: network, callId: CallId(id: id, accessHash: accessHash), log: debugLog).start() } }) } @@ -688,7 +688,8 @@ private final class CallSessionManagerContext { let keyHash = MTSha1(key) var keyId: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) memcpy(&keyId, bytes.advanced(by: keyHash.count - 8), 8) } @@ -891,7 +892,8 @@ private final class CallSessionManagerContext { let keyHash = MTSha1(key) var keyId: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) memcpy(&keyId, bytes.advanced(by: keyHash.count - 8), 8) } @@ -1267,9 +1269,9 @@ private func dropCallSession(network: Network, addUpdates: @escaping (Api.Update switch update { case .updatePhoneCall(let phoneCall): switch phoneCall { - case.phoneCallDiscarded(let values): - reportRating = (values.flags & (1 << 2)) != 0 - sendDebugLogs = (values.flags & (1 << 3)) != 0 + case let .phoneCallDiscarded(flags, _, _, _): + reportRating = (flags & (1 << 2)) != 0 + sendDebugLogs = (flags & (1 << 3)) != 0 default: break } diff --git a/submodules/TelegramCore/Sources/State/ChatHistoryPreloadManager.swift b/submodules/TelegramCore/Sources/State/ChatHistoryPreloadManager.swift index f20a18ac61..252e688601 100644 --- a/submodules/TelegramCore/Sources/State/ChatHistoryPreloadManager.swift +++ b/submodules/TelegramCore/Sources/State/ChatHistoryPreloadManager.swift @@ -447,7 +447,7 @@ final class ChatHistoryPreloadManager { switch index.entity { case let .peer(peerId): - Logger.shared.log("HistoryPreload", "view \(peerId) hole \(updatedHole) isUpdated: \(holeIsUpdated)") + Logger.shared.log("HistoryPreload", "view \(peerId) hole \(String(describing: updatedHole)) isUpdated: \(holeIsUpdated)") } if previousHole != updatedHole { diff --git a/submodules/TelegramCore/Sources/State/ContactSyncManager.swift b/submodules/TelegramCore/Sources/State/ContactSyncManager.swift index c7ceaded56..f4388c6d3c 100644 --- a/submodules/TelegramCore/Sources/State/ContactSyncManager.swift +++ b/submodules/TelegramCore/Sources/State/ContactSyncManager.swift @@ -197,7 +197,6 @@ private final class ContactSyncManagerImpl { disposable.add( (syncContactsOnce(network: self.network, postbox: self.postbox, accountPeerId: self.accountPeerId) |> mapToSignal { _ -> Signal in - return .complete() } |> then(importSignal) |> deliverOn(self.queue) @@ -250,8 +249,8 @@ private func pushDeviceContacts(postbox: Postbox, network: Network, importableCo if let updatedData = importableContacts[number] { if let value = value as? TelegramDeviceContactImportedData { switch value { - case let .imported(imported): - if imported.data != updatedData { + case let .imported(data, _): + if data != updatedData { updatedDataIdentifiers.insert(identifier) } case .retryLater: diff --git a/submodules/TelegramCore/Sources/State/FetchChatList.swift b/submodules/TelegramCore/Sources/State/FetchChatList.swift index 3bf3163eeb..addfcbae94 100644 --- a/submodules/TelegramCore/Sources/State/FetchChatList.swift +++ b/submodules/TelegramCore/Sources/State/FetchChatList.swift @@ -134,10 +134,10 @@ private func parseDialogs(apiDialogs: [Api.Dialog], apiMessages: [Api.Message], } notificationSettings[peerId] = TelegramPeerNotificationSettings(apiSettings: apiNotificationSettings) - case let .dialogFolder(dialogFolder): - switch dialogFolder.folder { - case let .folder(folder): - referencedFolders[PeerGroupId(rawValue: folder.id)] = PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: dialogFolder.unreadMutedMessagesCount, chatCount: dialogFolder.unreadMutedPeersCount)) + case let .dialogFolder(_, folder, _, _, unreadMutedPeersCount, _, unreadMutedMessagesCount, _): + switch folder { + case let .folder(_, id, _, _): + referencedFolders[PeerGroupId(rawValue: id)] = PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: unreadMutedMessagesCount, chatCount: unreadMutedPeersCount)) } } } diff --git a/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift b/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift index ea190a7647..ddcde51c86 100644 --- a/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift +++ b/submodules/TelegramCore/Sources/State/HistoryViewStateValidation.swift @@ -228,9 +228,9 @@ final class HistoryViewStateValidationContexts { completedMessageIds.append(messageId) } } - for messageId in completedMessageIds { - //context.batchReferences.removeValue(forKey: messageId) - } + /*for messageId in completedMessageIds { + context.batchReferences.removeValue(forKey: messageId) + }*/ } })) } diff --git a/submodules/TelegramCore/Sources/State/ManagedChatListHoles.swift b/submodules/TelegramCore/Sources/State/ManagedChatListHoles.swift index eecc2c16ca..920f6040ac 100644 --- a/submodules/TelegramCore/Sources/State/ManagedChatListHoles.swift +++ b/submodules/TelegramCore/Sources/State/ManagedChatListHoles.swift @@ -50,7 +50,7 @@ func managedChatListHoles(network: Network, postbox: Postbox, accountPeerId: Pee return lhs.hole.index > rhs.hole.index }) - if let preferencesView = combinedView.views[filtersKey] as? PreferencesView, let filtersState = preferencesView.values[PreferencesKeys.chatListFilters] as? ChatListFiltersState, !filtersState.filters.isEmpty { + if let preferencesView = combinedView.views[filtersKey] as? PreferencesView, let filtersState = preferencesView.values[PreferencesKeys.chatListFilters]?.get(ChatListFiltersState.self), !filtersState.filters.isEmpty { if let topRootHole = combinedView.views[topRootHoleKey] as? AllChatListHolesView, let hole = topRootHole.latestHole { let entry = ChatListHolesEntry(groupId: .root, hole: hole) if !entries.contains(entry) { diff --git a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift index 657ff3f395..bbe40b75f0 100644 --- a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift @@ -12,9 +12,9 @@ func managedConfigurationUpdates(accountManager: AccountManager mapToSignal { result -> Signal in return postbox.transaction { transaction -> Signal in switch result { - case let .config(config): + case let .config(flags, _, _, _, _, dcOptions, _, chatSizeMax, megagroupSizeMax, forwardedCountMax, _, _, _, _, _, _, _, _, savedGifsLimit, editTimeLimit, revokeTimeLimit, revokePmTimeLimit, _, stickersRecentLimit, _, _, _, pinnedDialogsCountMax, pinnedInfolderCountMax, _, _, _, _, _, autoupdateUrlPrefix, gifSearchUsername, venueSearchUsername, imgSearchUsername, _, captionLengthMax, _, webfileDcId, suggestedLangCode, langPackVersion, baseLangPackVersion): var addressList: [Int: [MTDatacenterAddress]] = [:] - for option in config.dcOptions { + for option in dcOptions { switch option { case let .dcOption(flags, id, ipAddress, port, secret): let preferForMedia = (flags & (1 << 1)) != 0 @@ -33,24 +33,24 @@ func managedConfigurationUpdates(accountManager: AccountManager Signal in let (primary, secondary) = getLocalization(transaction) var invalidateLocalization = false - if primary.version != config.langPackVersion { + if primary.version != langPackVersion { invalidateLocalization = true } - if let secondary = secondary, let baseLangPackVersion = config.baseLangPackVersion { + if let secondary = secondary, let baseLangPackVersion = baseLangPackVersion { if secondary.version != baseLangPackVersion { invalidateLocalization = true } diff --git a/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift b/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift index ec6e9b2609..04f174b2a0 100644 --- a/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/State/ManagedGlobalNotificationSettings.swift @@ -15,6 +15,7 @@ public func updateGlobalNotificationSettingsInteractively(postbox: Postbox, _ f: return PreferencesEntry(GlobalNotificationSettings(toBeSynchronized: settings, remote: settings)) } }) + transaction.globalNotificationSettingsUpdated() } } @@ -83,6 +84,7 @@ func managedGlobalNotificationSettings(postbox: Postbox, network: Network) -> Si return PreferencesEntry(GlobalNotificationSettings(toBeSynchronized: nil, remote: settings)) } }) + transaction.globalNotificationSettingsUpdated() } } case let .push(settings): @@ -95,6 +97,7 @@ func managedGlobalNotificationSettings(postbox: Postbox, network: Network) -> Si return current } }) + transaction.globalNotificationSettingsUpdated() }) } } diff --git a/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift index 9d1f803070..7f7dfd8d33 100644 --- a/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedProxyInfoUpdates.swift @@ -88,7 +88,7 @@ func managedPromoInfoUpdates(postbox: Postbox, network: Network, viewTracker: Ac switch data { case .promoDataEmpty: transaction.replaceAdditionalChatListItems([]) - case let .promoData(_, expires, peer, chats, users, psaType, psaMessage): + case let .promoData(_, _, peer, chats, users, psaType, psaMessage): var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] for chat in chats { diff --git a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift index 146d0ac618..43f2a25c32 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSecretChatOutgoingOperations.swift @@ -222,7 +222,8 @@ private func initialHandshakeAccept(postbox: Postbox, network: Network, peerId: let keyHash = MTSha1(key) var keyFingerprint: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } @@ -324,7 +325,8 @@ private func pfsAcceptKey(postbox: Postbox, network: Network, peerId: PeerId, la let keyHash = MTSha1(key) var keyFingerprint: Int64 = 0 - keyHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + keyHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) memcpy(&keyFingerprint, bytes.advanced(by: keyHash.count - 8), 8) } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift index f780347062..9284272950 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeGroupMessageStats.swift @@ -88,11 +88,11 @@ private func synchronizeGroupMessageStats(postbox: Postbox, network: Network, gr return postbox.transaction { transaction in if let result = result { switch result { - case let .peerDialogs(peerDialogs): - for dialog in peerDialogs.dialogs { + case let .peerDialogs(dialogs, _, _, _, _): + for dialog in dialogs { switch dialog { - case let .dialogFolder(dialogFolder): - transaction.resetPeerGroupSummary(groupId: groupId, namespace: namespace, summary: PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: dialogFolder.unreadMutedMessagesCount, chatCount: dialogFolder.unreadMutedPeersCount))) + case let .dialogFolder(_, _, _, _, unreadMutedPeersCount, _, unreadMutedMessagesCount, _): + transaction.resetPeerGroupSummary(groupId: groupId, namespace: namespace, summary: PeerGroupUnreadCountersSummary(all: PeerGroupUnreadCounters(messageCount: unreadMutedMessagesCount, chatCount: unreadMutedPeersCount))) case .dialog: assertionFailure() break diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift index b482aa427f..b5f921c7db 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeInstalledStickerPacksOperations.swift @@ -396,7 +396,6 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, let sequence = request |> retryRequest |> mapError { _ -> SynchronizeInstalledStickerPacksError in - return .restart } |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Signal in @@ -444,7 +443,6 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, } return resolveStickerPacks(network: network, remoteInfos: resolveRemoteInfos, localInfos: localInfos) |> mapError { _ -> SynchronizeInstalledStickerPacksError in - return .restart } |> mapToSignal { replaceItems -> Signal in return postbox.transaction { transaction -> Signal in @@ -481,8 +479,7 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, return ( storeSignal - |> mapError { _ -> SynchronizeInstalledStickerPacksError in return .restart - } + |> mapError { _ -> SynchronizeInstalledStickerPacksError in } ) |> then(.fail(.done)) } @@ -567,7 +564,7 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, let resolvedItems = resolveStickerPacks(network: network, remoteInfos: resultingInfos, localInfos: localInfos) return combineLatest(archivedOrRemovedIds, resolvedItems) - |> mapError { _ -> SynchronizeInstalledStickerPacksError in return .restart } + |> mapError { _ -> SynchronizeInstalledStickerPacksError in } |> mapToSignal { archivedOrRemovedIds, replaceItems -> Signal in return (postbox.transaction { transaction -> Signal in let finalCheckLocalCollectionInfos = transaction.getItemCollectionsInfos(namespace: collectionNamespace).map { $0.1 as! StickerPackCollectionInfo } @@ -590,7 +587,6 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, return .complete() } |> mapError { _ -> SynchronizeInstalledStickerPacksError in - return .restart }) |> switchToLatest |> then(.fail(.done)) @@ -598,7 +594,6 @@ private func continueSynchronizeInstalledStickerPacks(transaction: Transaction, } } |> mapError { _ -> SynchronizeInstalledStickerPacksError in - return .restart } |> switchToLatest } diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift index e2955b7659..bdbf6a3984 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizeMarkAllUnseenPersonalMessagesOperations.swift @@ -128,12 +128,12 @@ private func synchronizeMarkAllUnseen(transaction: Transaction, postbox: Postbox switch result { case let .messages(messages, _, _): return .single(messages.compactMap({ $0.id() })) - case let .channelMessages(channelMessages): - return .single(channelMessages.messages.compactMap({ $0.id() })) + case let .channelMessages(_, _, _, _, messages, _, _): + return .single(messages.compactMap({ $0.id() })) case .messagesNotModified: return .single([]) - case let .messagesSlice(messagesSlice): - return .single(messagesSlice.messages.compactMap({ $0.id() })) + case let .messagesSlice(_, _, _, _, messages, _, _): + return .single(messages.compactMap({ $0.id() })) } } |> mapToSignal { ids -> Signal in diff --git a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift index bac5ff138d..0c45508c65 100644 --- a/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedSynchronizePinnedChatsOperations.swift @@ -115,8 +115,6 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, switch item { case let .peer(peerId): return peerId.namespace != Namespaces.Peer.SecretChat - default: - return true } } let localItemIds = transaction.getPinnedItemIds(groupId: groupId) @@ -124,8 +122,6 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, switch item { case let .peer(peerId): return peerId.namespace != Namespaces.Peer.SecretChat - default: - return true } } @@ -167,7 +163,7 @@ private func synchronizePinnedChats(transaction: Transaction, postbox: Postbox, var apiChannelPts: Int32? let apiNotificationSettings: Api.PeerNotifySettings switch dialog { - case let .dialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, peerNotificationSettings, pts, _, _): + case let .dialog(flags, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, _, peerNotificationSettings, pts, _, _): apiPeer = peer apiTopMessage = topMessage apiReadInboxMaxId = readInboxMaxId diff --git a/submodules/TelegramCore/Sources/State/PendingMessageManager.swift b/submodules/TelegramCore/Sources/State/PendingMessageManager.swift index f2fc31cf0c..c04143b6cd 100644 --- a/submodules/TelegramCore/Sources/State/PendingMessageManager.swift +++ b/submodules/TelegramCore/Sources/State/PendingMessageManager.swift @@ -816,7 +816,6 @@ public final class PendingMessageManager { if let strongSelf = self { return strongSelf.applySentGroupMessages(postbox: postbox, stateManager: stateManager, messages: messages.map { $0.0 }, result: result) |> mapError { _ -> MTRpcError in - return MTRpcError(errorCode: 400, errorDescription: "empty") } } else { return .never() @@ -1058,12 +1057,10 @@ public final class PendingMessageManager { case .acknowledged: return strongSelf.applyAcknowledgedMessage(postbox: postbox, message: message) |> mapError { _ -> MTRpcError in - return MTRpcError(errorCode: 400, errorDescription: "internal") } case let .result(result): return strongSelf.applySentMessage(postbox: postbox, stateManager: stateManager, message: message, result: result) |> mapError { _ -> MTRpcError in - return MTRpcError(errorCode: 400, errorDescription: "internal") } } } diff --git a/submodules/TelegramCore/Sources/State/ProcessSecretChatIncomingDecryptedOperations.swift b/submodules/TelegramCore/Sources/State/ProcessSecretChatIncomingDecryptedOperations.swift index 80816b4681..17d268279b 100644 --- a/submodules/TelegramCore/Sources/State/ProcessSecretChatIncomingDecryptedOperations.swift +++ b/submodules/TelegramCore/Sources/State/ProcessSecretChatIncomingDecryptedOperations.swift @@ -510,17 +510,17 @@ extension SecretChatServiceAction { extension StoreMessage { convenience init?(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32, timestamp: Int32, apiMessage: SecretApi8.DecryptedMessage, file: SecretChatFileReference?) { switch apiMessage { - case let .decryptedMessage(randomId, _, message, media): + case let .decryptedMessage(randomId, _, message, _): self.init(id: MessageId(peerId: peerId, namespace: Namespaces.Message.SecretIncoming, id: tagLocalIndex), globallyUniqueId: randomId, groupingKey: nil, threadId: nil, timestamp: timestamp, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, authorId: authorId, text: message, attributes: [], media: []) case let .decryptedMessageService(randomId, _, action): switch action { - case let .decryptedMessageActionDeleteMessages(randomIds): + case .decryptedMessageActionDeleteMessages: return nil case .decryptedMessageActionFlushHistory: return nil - case let .decryptedMessageActionNotifyLayer(layer): + case .decryptedMessageActionNotifyLayer: return nil - case let .decryptedMessageActionReadMessages(randomIds): + case .decryptedMessageActionReadMessages: return nil case .decryptedMessageActionScreenshotMessages: self.init(id: MessageId(peerId: peerId, namespace: Namespaces.Message.SecretIncoming, id: tagLocalIndex), globallyUniqueId: randomId, groupingKey: nil, threadId: nil, timestamp: timestamp, flags: [.Incoming], tags: [], globalTags: [], localTags: [], forwardInfo: nil, authorId: authorId, text: "", attributes: [], media: [TelegramMediaAction(action: .historyScreenshot)]) @@ -824,7 +824,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 return (StoreMessage(id: MessageId(peerId: peerId, namespace: Namespaces.Message.SecretIncoming, id: tagLocalIndex), globallyUniqueId: randomId, groupingKey: nil, threadId: nil, timestamp: timestamp, flags: [.Incoming], tags: tags, globalTags: globalTags, localTags: [], forwardInfo: nil, authorId: authorId, text: text, attributes: attributes, media: parsedMedia), resources) case let .decryptedMessageService(randomId, action): switch action { - case let .decryptedMessageActionDeleteMessages(randomIds): + case .decryptedMessageActionDeleteMessages: return nil case .decryptedMessageActionFlushHistory: return nil @@ -977,7 +977,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 let fileMedia = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.CloudSecretFile, id: file.id), partialReference: nil, resource: file.resource(key: SecretFileEncryptionKey(aesKey: key.makeData(), aesIv: iv.makeData()), decryptedSize: size), previewRepresentations: previewRepresentations, videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: Int(size), attributes: parsedAttributes) parsedMedia.append(fileMedia) } - case let .decryptedMessageMediaExternalDocument(id, accessHash, date, mimeType, size, thumb, dcId, attributes): + case let .decryptedMessageMediaExternalDocument(id, accessHash, _, mimeType, size, thumb, dcId, attributes): var parsedAttributes: [TelegramMediaFileAttribute] = [] for attribute in attributes { if let parsedAttribute = TelegramMediaFileAttribute(attribute) { @@ -1215,7 +1215,7 @@ private func parseMessage(peerId: PeerId, authorId: PeerId, tagLocalIndex: Int32 let fileMedia = TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.CloudSecretFile, id: file.id), partialReference: nil, resource: file.resource(key: SecretFileEncryptionKey(aesKey: key.makeData(), aesIv: iv.makeData()), decryptedSize: size), previewRepresentations: previewRepresentations, videoThumbnails: [], immediateThumbnailData: nil, mimeType: mimeType, size: Int(size), attributes: parsedAttributes) parsedMedia.append(fileMedia) } - case let .decryptedMessageMediaExternalDocument(id, accessHash, date, mimeType, size, thumb, dcId, attributes): + case let .decryptedMessageMediaExternalDocument(id, accessHash, _, mimeType, size, thumb, dcId, attributes): var parsedAttributes: [TelegramMediaFileAttribute] = [] for attribute in attributes { if let parsedAttribute = TelegramMediaFileAttribute(attribute) { diff --git a/submodules/TelegramCore/Sources/State/Serialization.swift b/submodules/TelegramCore/Sources/State/Serialization.swift index 6186d380d5..06a364da91 100644 --- a/submodules/TelegramCore/Sources/State/Serialization.swift +++ b/submodules/TelegramCore/Sources/State/Serialization.swift @@ -246,9 +246,9 @@ public class Serialization: NSObject, MTSerialization { return { response -> MTDatacenterAddressListData? in if let config = parser.parse(Buffer(data: response)) { switch config { - case let .config(config): + case let .config(_, _, _, _, _, dcOptions, _, _, _, _, _, _,_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): var addressDict: [NSNumber: [Any]] = [:] - for option in config.dcOptions { + for option in dcOptions { switch option { case let .dcOption(flags, id, ipAddress, port, secret): if addressDict[id as NSNumber] == nil { diff --git a/submodules/TelegramCore/Sources/State/StickerManagement.swift b/submodules/TelegramCore/Sources/State/StickerManagement.swift index f6109865d7..34a65ab014 100644 --- a/submodules/TelegramCore/Sources/State/StickerManagement.swift +++ b/submodules/TelegramCore/Sources/State/StickerManagement.swift @@ -4,13 +4,13 @@ import Postbox import SwiftSignalKit -private func hashForIdsReverse(_ ids: [Int64]) -> Int32 { +private func hashForIdsReverse(_ ids: [Int64]) -> Int64 { var acc: UInt64 = 0 for id in ids { combineInt64Hash(&acc, with: UInt64(bitPattern: id)) } - return Int32(bitPattern: UInt32(clamping: acc & UInt64(0x7FFFFFFF))) + return Int64(bitPattern: acc) } func manageStickerPacks(network: Network, postbox: Postbox) -> Signal { @@ -35,8 +35,8 @@ func updatedFeaturedStickerPacks(network: Network, postbox: Postbox) -> Signal retryRequest |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Void in diff --git a/submodules/TelegramCore/Sources/State/SynchronizeConsumeMessageContentsOperation.swift b/submodules/TelegramCore/Sources/State/SynchronizeConsumeMessageContentsOperation.swift index 62b40f9239..e2b071778d 100644 --- a/submodules/TelegramCore/Sources/State/SynchronizeConsumeMessageContentsOperation.swift +++ b/submodules/TelegramCore/Sources/State/SynchronizeConsumeMessageContentsOperation.swift @@ -2,7 +2,7 @@ import Postbox func addSynchronizeConsumeMessageContentsOperation(transaction: Transaction, messageIds: [MessageId]) { for (peerId, messageIds) in messagesIdsGroupedByPeerId(Set(messageIds)) { - var updateLocalIndex: Int32? + let updateLocalIndex: Int32? = nil /*transaction.operationLogEnumerateEntries(peerId: peerId, tag: OperationLogTags.SynchronizeConsumeMessageContents, { entry in updateLocalIndex = entry.tagLocalIndex return false diff --git a/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift b/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift index 1cfa73aaa3..c704b5cd74 100644 --- a/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift +++ b/submodules/TelegramCore/Sources/State/SynchronizePeerReadState.swift @@ -247,7 +247,6 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: } return pushSignal |> mapError { _ -> PeerReadStateValidationError in - return .retry } |> mapToSignal { _ -> Signal in return .complete() @@ -287,7 +286,6 @@ private func pushPeerReadState(network: Network, postbox: Postbox, stateManager: return pushSignal |> mapError { _ -> PeerReadStateValidationError in - return .retry } |> mapToSignal { _ -> Signal in return .complete() diff --git a/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift b/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift index cb24371e7f..34eeb16369 100644 --- a/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift +++ b/submodules/TelegramCore/Sources/State/SynchronizeSavedStickersOperation.swift @@ -92,7 +92,7 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe if let stickerStringRepresentations = stickerStringRepresentations { return postbox.transaction { transaction -> Void in addSavedSticker(transaction: transaction, file: file, stringRepresentations: stickerStringRepresentations) - } |> mapError { _ in return AddSavedStickerError.generic } + } |> mapError { _ -> AddSavedStickerError in } } else { return .fail(.notFound) } @@ -102,7 +102,7 @@ public func addSavedSticker(postbox: Postbox, network: Network, file: TelegramMe } } return .complete() - } |> mapError { _ in return AddSavedStickerError.generic } |> switchToLatest + } |> mapError { _ -> AddSavedStickerError in } |> switchToLatest } public func addSavedSticker(transaction: Transaction, file: TelegramMediaFile, stringRepresentations: [String]) { diff --git a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift index 91dcb3b5ef..7cd9d2e01a 100644 --- a/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift +++ b/submodules/TelegramCore/Sources/State/UpdatesApiUtils.swift @@ -60,8 +60,8 @@ extension Api.MessageMedia { case let .messageMediaWebPage(webPage): var result: [(MediaResource, Data)]? switch webPage { - case let .webPage(content): - if let photo = content.photo { + case let .webPage(_, _, _, _, _, _, _, _, _, photo, _, _, _, _, _, _, document, _, _): + if let photo = photo { if let photoResult = collectPreCachedResources(for: photo) { if result == nil { result = [] @@ -69,7 +69,7 @@ extension Api.MessageMedia { result!.append(contentsOf: photoResult) } } - if let file = content.document { + if let file = document { if let fileResult = collectPreCachedResources(for: file) { if result == nil { result = [] @@ -90,8 +90,8 @@ extension Api.MessageMedia { extension Api.Message { var rawId: Int32 { switch self { - case let .message(message): - return message.id + case let .message(_, id, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + return id case let .messageEmpty(_, id, _): return id case let .messageService(_, id, _, _, _, _, _, _): @@ -101,12 +101,8 @@ extension Api.Message { func id(namespace: MessageId.Namespace = Namespaces.Message.Cloud) -> MessageId? { switch self { - case let .message(message): - let flags = message.flags - let id = message.id - let fromId = message.fromId - - let peerId: PeerId = message.peerId.peerId + case let .message(_, id, _, messagePeerId, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + let peerId: PeerId = messagePeerId.peerId return MessageId(peerId: peerId, namespace: namespace, id: id) case let .messageEmpty(_, id, peerId): if let peerId = peerId { @@ -114,7 +110,7 @@ extension Api.Message { } else { return nil } - case let .messageService(flags, id, fromId, chatPeerId, _, _, _, _): + case let .messageService(_, id, _, chatPeerId, _, _, _, _): let peerId: PeerId = chatPeerId.peerId return MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: id) } @@ -122,10 +118,10 @@ extension Api.Message { var timestamp: Int32? { switch self { - case let .message(message): - return message.date - case let .messageService(messageService): - return messageService.date + case let .message(_, _, _, _, _, _, _, date, _, _, _, _, _, _, _, _, _, _, _, _): + return date + case let .messageService(_, _, _, _, _, date, _, _): + return date case .messageEmpty: return nil } @@ -133,8 +129,8 @@ extension Api.Message { var preCachedResources: [(MediaResource, Data)]? { switch self { - case let .message(message): - return message.media?.preCachedResources + case let .message(_, _, _, _, _, _, _, _, _, media, _, _, _, _, _, _, _, _, _, _): + return media?.preCachedResources default: return nil } @@ -144,14 +140,14 @@ extension Api.Message { extension Api.Chat { var peerId: PeerId { switch self { - case let .chat(chat): - return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chat.id)) + case let .chat(_, id, _, _, _, _, _, _, _, _): + return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) case let .chatEmpty(id): return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) case let .chatForbidden(id, _): return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(id)) - case let .channel(channel): - return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channel.id)) + case let .channel(_, id, _, _, _, _, _, _, _, _, _, _): + return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)) case let .channelForbidden(_, id, _, _, _): return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(id)) } diff --git a/submodules/TelegramCore/Sources/Suggestions.swift b/submodules/TelegramCore/Sources/Suggestions.swift index 36906c406f..e8e81c25e4 100644 --- a/submodules/TelegramCore/Sources/Suggestions.swift +++ b/submodules/TelegramCore/Sources/Suggestions.swift @@ -25,7 +25,7 @@ public func getServerProvidedSuggestions(account: Account) -> Signal<[ServerProv guard let view = views.views[key] as? PreferencesView else { return [] } - guard let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration else { + guard let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { return [] } guard let data = appConfiguration.data, let list = data["pending_suggestions"] as? [String] else { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift index 99595e9d22..40586d30fe 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AppConfiguration.swift @@ -12,15 +12,15 @@ public struct AppConfiguration: Codable, Equatable { self.data = data } - public init(decoder: PostboxDecoder) { - self.data = decoder.decodeObjectForKey("data", decoder: { JSON(decoder: $0) }) as? JSON + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.data = try container.decodeIfPresent(JSON.self, forKey: "data") } - public func encode(_ encoder: PostboxEncoder) { - if let data = self.data { - encoder.encodeObject(data, forKey: "data") - } else { - encoder.encodeNil(forKey: "data") - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encodeIfPresent(self.data, forKey: "data") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift index cc358b3c1e..10d47173cb 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift @@ -9,7 +9,9 @@ public final class CachedResolvedByNamePeer: PostboxCoding { let key: ValueBoxKey if let nameData = name.data(using: .utf8) { key = ValueBoxKey(length: nameData.count) - nameData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + nameData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(key.memory, bytes, nameData.count) } } else { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift index fa65be62e9..e83573796a 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CloudFileMediaResource.swift @@ -520,7 +520,7 @@ public struct LocalFileMediaResourceId: MediaResourceId, Hashable, Equatable { } } -public class LocalFileMediaResource: TelegramMediaResource { +public class LocalFileMediaResource: TelegramMediaResource, Codable { public let fileId: Int64 public let size: Int? @@ -541,6 +541,14 @@ public class LocalFileMediaResource: TelegramMediaResource { self.size = nil } } + + public required init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.fileId = try container.decode(Int64.self, forKey: "f") + self.isSecretRelated = try container.decodeIfPresent(Bool.self, forKey: "sr") ?? false + self.size = (try container.decodeIfPresent(Int32.self, forKey: "s")).flatMap(Int.init) + } public func encode(_ encoder: PostboxEncoder) { encoder.encodeInt64(self.fileId, forKey: "f") @@ -551,6 +559,14 @@ public class LocalFileMediaResource: TelegramMediaResource { encoder.encodeNil(forKey: "s") } } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.fileId, forKey: "f") + try container.encode(self.isSecretRelated, forKey: "sr") + try container.encodeIfPresent(self.size.flatMap(Int32.init), forKey: "s") + } public var id: MediaResourceId { return LocalFileMediaResourceId(fileId: self.fileId) diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_GlobalNotificationSettings.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_GlobalNotificationSettings.swift index 71b1b3138d..3b641ceddb 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_GlobalNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_GlobalNotificationSettings.swift @@ -1,6 +1,6 @@ import Postbox -public struct MessageNotificationSettings: Codable { +public struct MessageNotificationSettings: Codable, Equatable { public var enabled: Bool public var displayPreviews: Bool public var sound: PeerMessageSound @@ -21,14 +21,15 @@ public struct MessageNotificationSettings: Codable { self.enabled = ((try? container.decode(Int32.self, forKey: "e")) ?? 0) != 0 self.displayPreviews = ((try? container.decode(Int32.self, forKey: "p")) ?? 0) != 0 - self.sound = PeerMessageSound.decodeInline(container) + self.sound = try PeerMessageSound.decodeInline(container) } public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) - encoder.encodeInt32(self.enabled ? 1 : 0, forKey: "e") - encoder.encodeInt32(self.displayPreviews ? 1 : 0, forKey: "p") - self.sound.encodeInline(encoder) + try container.encode((self.enabled ? 1 : 0) as Int32, forKey: "e") + try container.encode((self.displayPreviews ? 1 : 0) as Int32, forKey: "p") + try self.sound.encodeInline(&container) } } @@ -52,18 +53,20 @@ public struct GlobalNotificationSettingsSet: Codable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) - self.privateChats = decoder.decodeObjectForKey("p", decoder: { MessageNotificationSettings(decoder: $0) }) as! MessageNotificationSettings - self.groupChats = decoder.decodeObjectForKey("g", decoder: { MessageNotificationSettings(decoder: $0) }) as! MessageNotificationSettings - self.channels = (decoder.decodeObjectForKey("c", decoder: { MessageNotificationSettings(decoder: $0) }) as? MessageNotificationSettings) ?? MessageNotificationSettings.defaultSettings - self.contactsJoined = decoder.decodeInt32ForKey("contactsJoined", orElse: 1) != 0 + self.privateChats = try container.decode(MessageNotificationSettings.self, forKey: "p") + self.groupChats = try container.decode(MessageNotificationSettings.self, forKey: "g") + self.channels = try container.decode(MessageNotificationSettings.self, forKey: "c") + + self.contactsJoined = (try container.decode(Int32.self, forKey: "contactsJoined")) != 0 } public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) - encoder.encodeObject(self.privateChats, forKey: "p") - encoder.encodeObject(self.groupChats, forKey: "g") - encoder.encodeObject(self.channels, forKey: "c") - encoder.encodeInt32(self.contactsJoined ? 1 : 0, forKey: "contactsJoined") + try container.encode(self.privateChats, forKey: "p") + try container.encode(self.groupChats, forKey: "g") + try container.encode(self.channels, forKey: "c") + try container.encode((self.contactsJoined ? 1 : 0) as Int32, forKey: "contactsJoined") } } @@ -89,7 +92,7 @@ public struct GlobalNotificationSettings: Codable { ) } - private func defaultIncludePeer(peer: Peer) -> Bool { + func defaultIncludePeer(peer: Peer) -> Bool { let settings = self.effective if peer is TelegramUser || peer is TelegramSecretChat { return settings.privateChats.enabled @@ -135,16 +138,14 @@ public struct GlobalNotificationSettings: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) - self.toBeSynchronized = decoder.decodeObjectForKey("s", decoder: { GlobalNotificationSettingsSet(decoder: $0) }) as? GlobalNotificationSettingsSet - self.remote = decoder.decodeObjectForKey("r", decoder: { GlobalNotificationSettingsSet(decoder: $0) }) as! GlobalNotificationSettingsSet + self.toBeSynchronized = try container.decodeIfPresent(GlobalNotificationSettingsSet.self, forKey: "s") + self.remote = try container.decode(GlobalNotificationSettingsSet.self, forKey: "r") } public func encode(to encoder: Encoder) throws { - if let toBeSynchronized = self.toBeSynchronized { - encoder.encodeObject(toBeSynchronized, forKey: "s") - } else { - encoder.encodeNil(forKey: "s") - } - encoder.encodeObject(self.remote, forKey: "r") + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encodeIfPresent(self.toBeSynchronized, forKey: "s") + try container.encode(self.remote, forKey: "r") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_JSON.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_JSON.swift index ef51457723..d656439ec7 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_JSON.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_JSON.swift @@ -1,6 +1,26 @@ import Postbox -public indirect enum JSON: PostboxCoding, Equatable { +public indirect enum JSON: Codable, Equatable { + private struct DictionaryKey: Codable, Hashable { + var key: String + + init(_ key: String) { + self.key = key + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.key = try container.decode(String.self, forKey: "k") + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.key, forKey: "k") + } + } + case null case number(Double) case string(String) @@ -17,47 +37,57 @@ public indirect enum JSON: PostboxCoding, Equatable { case dictionary = 5 } - public init(decoder: PostboxDecoder) { - switch decoder.decodeInt32ForKey("r", orElse: 0) { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + switch try container.decode(Int32.self, forKey: "r") { case ValueType.null.rawValue: self = .null case ValueType.number.rawValue: - self = .number(decoder.decodeDoubleForKey("v", orElse: 0.0)) + self = .number(try container.decode(Double.self, forKey: "v")) case ValueType.string.rawValue: - self = .string(decoder.decodeStringForKey("v", orElse: "")) + self = .string(try container.decode(String.self, forKey: "v")) case ValueType.bool.rawValue: - self = .bool(decoder.decodeBoolForKey("v", orElse: false)) + self = .bool(try container.decode(Bool.self, forKey: "v")) case ValueType.array.rawValue: - self = .array(decoder.decodeObjectArrayForKey("v")) + self = .array(try container.decode([JSON].self, forKey: "v")) case ValueType.dictionary.rawValue: - self = .dictionary(decoder.decodeObjectDictionaryForKey("v", keyDecoder: { $0.decodeStringForKey("k", orElse: "") - }, valueDecoder: { JSON(decoder: $0) })) + let dict = try container.decode([DictionaryKey: JSON].self, forKey: "v") + var mappedDict: [String: JSON] = [:] + for (key, value) in dict { + mappedDict[key.key] = value + } + self = .dictionary(mappedDict) default: self = .null } } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + switch self { case .null: - encoder.encodeInt32(ValueType.null.rawValue, forKey: "r") + try container.encode(ValueType.null.rawValue, forKey: "r") case let .number(value): - encoder.encodeInt32(ValueType.number.rawValue, forKey: "r") - encoder.encodeDouble(value, forKey: "v") + try container.encode(ValueType.number.rawValue, forKey: "r") + try container.encode(value, forKey: "v") case let .string(value): - encoder.encodeInt32(ValueType.string.rawValue, forKey: "r") - encoder.encodeString(value, forKey: "v") + try container.encode(ValueType.string.rawValue, forKey: "r") + try container.encode(value, forKey: "v") case let .bool(value): - encoder.encodeInt32(ValueType.bool.rawValue, forKey: "r") - encoder.encodeBool(value, forKey: "v") + try container.encode(ValueType.bool.rawValue, forKey: "r") + try container.encode(value, forKey: "v") case let .array(value): - encoder.encodeInt32(ValueType.array.rawValue, forKey: "r") - encoder.encodeObjectArray(value, forKey: "v") + try container.encode(ValueType.array.rawValue, forKey: "r") + try container.encode(value, forKey: "v") case let .dictionary(value): - encoder.encodeInt32(ValueType.dictionary.rawValue, forKey: "r") - encoder.encodeObjectDictionary(value, forKey: "v") { key, encoder in - encoder.encodeString(key, forKey: "k") + try container.encode(ValueType.dictionary.rawValue, forKey: "r") + var mappedDict: [DictionaryKey: JSON] = [:] + for (k, v) in value { + mappedDict[DictionaryKey(k)] = v } + try container.encode(mappedDict, forKey: "v") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_LimitsConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_LimitsConfiguration.swift index 82b78a4fbd..dc4533c506 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_LimitsConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_LimitsConfiguration.swift @@ -64,7 +64,7 @@ public struct LimitsConfiguration: Codable, Equatable { try container.encode(self.maxRecentStickerCount, forKey: "maxRecentStickerCount") try container.encode(self.maxMessageEditingInterval, forKey: "maxMessageEditingInterval") try container.encode(self.maxMediaCaptionLength, forKey: "maxMediaCaptionLength") - try container.encode(self.canRemoveIncomingMessagesInPrivateChats ? 1 : 0, forKey: "canRemoveIncomingMessagesInPrivateChats") + try container.encode((self.canRemoveIncomingMessagesInPrivateChats ? 1 : 0) as Int32, forKey: "canRemoveIncomingMessagesInPrivateChats") try container.encode(self.maxMessageRevokeInterval, forKey: "maxMessageRevokeInterval") try container.encode(self.maxMessageRevokeIntervalInPrivateChats, forKey: "maxMessageRevokeIntervalInPrivateChats") } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_MediaReference.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_MediaReference.swift index 089f3a275b..29fa4cf791 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_MediaReference.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_MediaReference.swift @@ -269,7 +269,7 @@ public enum AnyMediaReference: Equatable { return .stickerPack(stickerPack: stickerPack) case .savedGif: return .savedGif - case let .avatarList(peer, media): + case .avatarList: return nil } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_SecretChatState.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_SecretChatState.swift index 48be226cf4..88a5006690 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_SecretChatState.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_SecretChatState.swift @@ -23,11 +23,15 @@ public struct SecretChatKeySha1Fingerprint: PostboxCoding, Equatable { var k0: Int64 = 0 var k1: Int64 = 0 var k2: Int32 = 0 - digest.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + digest.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int64.self) + k0 = bytes.pointee k1 = bytes.advanced(by: 1).pointee } - digest.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + digest.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int32.self) + k2 = bytes.advanced(by: 4).pointee } self.k0 = k0 @@ -56,11 +60,15 @@ public struct SecretChatKeySha1Fingerprint: PostboxCoding, Equatable { public func data() -> Data { var data = Data() data.count = 20 - data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + data.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int64.self) + bytes.pointee = self.k0 bytes.advanced(by: 1).pointee = self.k1 } - data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + data.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int32.self) + bytes.advanced(by: 4).pointee = self.k2 } return data @@ -92,7 +100,9 @@ public struct SecretChatKeySha256Fingerprint: PostboxCoding, Equatable { var k1: Int64 = 0 var k2: Int64 = 0 var k3: Int64 = 0 - digest.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + digest.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int64.self) + k0 = bytes.pointee k1 = bytes.advanced(by: 1).pointee k2 = bytes.advanced(by: 2).pointee @@ -128,7 +138,9 @@ public struct SecretChatKeySha256Fingerprint: PostboxCoding, Equatable { public func data() -> Data { var data = Data() data.count = 32 - data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + data.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int64.self) + bytes.pointee = self.k0 bytes.advanced(by: 1).pointee = self.k1 bytes.advanced(by: 2).pointee = self.k2 diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_StandaloneAccountTransaction.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_StandaloneAccountTransaction.swift index 2d16cfdff6..6127a574fd 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_StandaloneAccountTransaction.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_StandaloneAccountTransaction.swift @@ -34,37 +34,63 @@ public let telegramPostboxSeedConfiguration: SeedConfiguration = { globalMessageIdsPeerIdNamespaces.insert(GlobalMessageIdsNamespace(peerIdNamespace: peerIdNamespace, messageIdNamespace: Namespaces.Message.Cloud)) } - return SeedConfiguration(globalMessageIdsPeerIdNamespaces: globalMessageIdsPeerIdNamespaces, initializeChatListWithHole: (topLevel: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt64Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1)), groups: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt64Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1))), messageHoles: messageHoles, upgradedMessageHoles: upgradedMessageHoles, messageThreadHoles: messageThreadHoles, existingMessageTags: MessageTags.all, messageTagsWithSummary: [.unseenPersonalMessage, .pinned], existingGlobalMessageTags: GlobalMessageTags.all, peerNamespacesRequiringMessageTextIndex: [Namespaces.Peer.SecretChat], peerSummaryCounterTags: { peer, isContact in - if let peer = peer as? TelegramUser { - if peer.botInfo != nil { - return .bot - } else if isContact { - return .contact + return SeedConfiguration( + globalMessageIdsPeerIdNamespaces: globalMessageIdsPeerIdNamespaces, + initializeChatListWithHole: ( + topLevel: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt64Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1)), + groups: ChatListHole(index: MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: PeerId.Id._internalFromInt64Value(0)), namespace: Namespaces.Message.Cloud, id: 1), timestamp: Int32.max - 1)) + ), + messageHoles: messageHoles, + upgradedMessageHoles: upgradedMessageHoles, + messageThreadHoles: messageThreadHoles, + existingMessageTags: MessageTags.all, + messageTagsWithSummary: [.unseenPersonalMessage, .pinned], + existingGlobalMessageTags: GlobalMessageTags.all, + peerNamespacesRequiringMessageTextIndex: [Namespaces.Peer.SecretChat], + peerSummaryCounterTags: { peer, isContact in + if let peer = peer as? TelegramUser { + if peer.botInfo != nil { + return .bot + } else if isContact { + return .contact + } else { + return .nonContact + } + } else if let _ = peer as? TelegramGroup { + return .group + } else if let _ = peer as? TelegramSecretChat { + return .nonContact + } else if let channel = peer as? TelegramChannel { + switch channel.info { + case .broadcast: + return .channel + case .group: + if channel.username != nil { + return .group + } else { + return .group + } + } } else { + assertionFailure() return .nonContact } - } else if let _ = peer as? TelegramGroup { - return .group - } else if let _ = peer as? TelegramSecretChat { - return .nonContact - } else if let channel = peer as? TelegramChannel { - switch channel.info { - case .broadcast: - return .channel - case .group: - if channel.username != nil { - return .group - } else { - return .group - } + }, + additionalChatListIndexNamespace: Namespaces.Message.Cloud, + messageNamespacesRequiringGroupStatsValidation: [Namespaces.Message.Cloud], + defaultMessageNamespaceReadStates: [Namespaces.Message.Local: .idBased(maxIncomingReadId: 0, maxOutgoingReadId: 0, maxKnownId: 0, count: 0, markedUnread: false)], + chatMessagesNamespaces: Set([Namespaces.Message.Cloud, Namespaces.Message.Local, Namespaces.Message.SecretIncoming]), + getGlobalNotificationSettings: { transaction -> PostboxGlobalNotificationSettings? in + (transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self)).flatMap { settings in + return PostboxGlobalNotificationSettings(defaultIncludePeer: { peer in + return settings.defaultIncludePeer(peer: peer) + }) } - } else { - assertionFailure() - return .nonContact - } - }, additionalChatListIndexNamespace: Namespaces.Message.Cloud, messageNamespacesRequiringGroupStatsValidation: [Namespaces.Message.Cloud], defaultMessageNamespaceReadStates: [Namespaces.Message.Local: .idBased(maxIncomingReadId: 0, maxOutgoingReadId: 0, maxKnownId: 0, count: 0, markedUnread: false)], chatMessagesNamespaces: Set([Namespaces.Message.Cloud, Namespaces.Message.Local, Namespaces.Message.SecretIncoming]), globalNotificationSettingsPreferencesKey: { transaction in - return transaction.getPreferencesEntry(PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) - }, defaultGlobalNotificationSettings: GlobalNotificationSettings.defaultSettings) + }, + defaultGlobalNotificationSettings: PostboxGlobalNotificationSettings(defaultIncludePeer: { peer in + return GlobalNotificationSettings.defaultSettings.defaultIncludePeer(peer: peer) + }) + ) }() public enum AccountTransactionError { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_SynchronizeAppLogEventsOperation.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_SynchronizeAppLogEventsOperation.swift index de56774577..3970b41e43 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_SynchronizeAppLogEventsOperation.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_SynchronizeAppLogEventsOperation.swift @@ -5,18 +5,25 @@ private enum SynchronizeAppLogEventsOperationContentType: Int32 { case sync } -public enum SynchronizeAppLogEventsOperationContent: PostboxCoding { +public enum SynchronizeAppLogEventsOperationContent: Codable { case add(time: Double, type: String, peerId: PeerId?, data: JSON) case sync - public init(decoder: PostboxDecoder) { - switch decoder.decodeInt32ForKey("r", orElse: 0) { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + switch try container.decode(Int32.self, forKey: "r") { case SynchronizeAppLogEventsOperationContentType.add.rawValue: var peerId: PeerId? - if let id = decoder.decodeOptionalInt64ForKey("p") { + if let id = try? container.decodeIfPresent(Int64.self, forKey: "p") { peerId = PeerId(id) } - self = .add(time: decoder.decodeDoubleForKey("tm", orElse: 0.0), type: decoder.decodeStringForKey("t", orElse: ""), peerId: peerId, data: decoder.decodeObjectForKey("d", decoder: { JSON(decoder: $0) }) as! JSON) + self = .add( + time: try container.decode(Double.self, forKey: "tm"), + type: try container.decode(String.self, forKey: "t"), + peerId: peerId, + data: try container.decode(JSON.self, forKey: "d") + ) case SynchronizeAppLogEventsOperationContentType.sync.rawValue: self = .sync default: @@ -24,37 +31,47 @@ public enum SynchronizeAppLogEventsOperationContent: PostboxCoding { self = .sync } } - - public func encode(_ encoder: PostboxEncoder) { + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + switch self { case let .add(time, type, peerId, data): - encoder.encodeInt32(SynchronizeAppLogEventsOperationContentType.add.rawValue, forKey: "r") - encoder.encodeDouble(time, forKey: "tm") - encoder.encodeString(type, forKey: "t") - if let peerId = peerId { - encoder.encodeInt64(peerId.toInt64(), forKey: "p") - } else { - encoder.encodeNil(forKey: "p") - } - encoder.encodeObject(data, forKey: "d") + try container.encode(SynchronizeAppLogEventsOperationContentType.add.rawValue, forKey: "r") + try container.encode(time, forKey: "tm") + try container.encode(type, forKey: "t") + try container.encodeIfPresent(peerId?.toInt64(), forKey: "p") + try container.encode(data, forKey: "d") case .sync: - encoder.encodeInt32(SynchronizeAppLogEventsOperationContentType.sync.rawValue, forKey: "r") + try container.encode(SynchronizeAppLogEventsOperationContentType.sync.rawValue, forKey: "r") } } } -public final class SynchronizeAppLogEventsOperation: PostboxCoding { +public final class SynchronizeAppLogEventsOperation: Codable, PostboxCoding { public let content: SynchronizeAppLogEventsOperationContent public init(content: SynchronizeAppLogEventsOperationContent) { self.content = content } - public init(decoder: PostboxDecoder) { - self.content = decoder.decodeObjectForKey("c", decoder: { SynchronizeAppLogEventsOperationContent(decoder: $0) }) as! SynchronizeAppLogEventsOperationContent + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.content = try container.decode(SynchronizeAppLogEventsOperationContent.self, forKey: "c") } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.content, forKey: "c") + } + + public init(decoder: PostboxDecoder) { + self.content = decoder.decode(SynchronizeAppLogEventsOperationContent.self, forKey: "c")! + } + public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.content, forKey: "c") + encoder.encode(self.content, forKey: "c") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramPeerNotificationSettings.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramPeerNotificationSettings.swift index 529efd76d7..afac21e3ea 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramPeerNotificationSettings.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramPeerNotificationSettings.swift @@ -59,6 +59,37 @@ public enum PeerMessageSound: Equatable { return .bundledModern(id: 0) } } + + static func decodeInline(_ container: PostboxDecoder) -> PeerMessageSound { + switch container.decodeInt32ForKey("s.v", orElse: 0) { + case PeerMessageSoundValue.none.rawValue: + return .none + case PeerMessageSoundValue.bundledModern.rawValue: + return .bundledModern(id: container.decodeInt32ForKey("s.i", orElse: 0)) + case PeerMessageSoundValue.bundledClassic.rawValue: + return .bundledClassic(id: container.decodeInt32ForKey("s.i", orElse: 0)) + case PeerMessageSoundValue.default.rawValue: + return .default + default: + assertionFailure() + return .bundledModern(id: 0) + } + } + + func encodeInline(_ container: inout KeyedEncodingContainer) throws { + switch self { + case .none: + try container.encode(PeerMessageSoundValue.none.rawValue, forKey: "s.v") + case let .bundledModern(id): + try container.encode(PeerMessageSoundValue.bundledModern.rawValue, forKey: "s.v") + try container.encode(id, forKey: "s.i") + case let .bundledClassic(id): + try container.encode(PeerMessageSoundValue.bundledClassic.rawValue, forKey: "s.v") + try container.encode(id, forKey: "s.i") + case .default: + try container.encode(PeerMessageSoundValue.default.rawValue, forKey: "s.v") + } + } func encodeInline(_ encoder: PostboxEncoder) { switch self { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramTheme.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramTheme.swift index 3a7c4d34f4..5253f971e7 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramTheme.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramTheme.swift @@ -14,7 +14,7 @@ public extension UInt32 { } } -public final class TelegramThemeSettings: PostboxCoding, Codable, Equatable { +public final class TelegramThemeSettings: PostboxCoding, Equatable { public static func == (lhs: TelegramThemeSettings, rhs: TelegramThemeSettings) -> Bool { if lhs.baseTheme != rhs.baseTheme { return false @@ -110,7 +110,7 @@ public final class TelegramThemeSettings: PostboxCoding, Codable, Equatable { } } -public final class TelegramTheme: Codable, OrderedItemListEntryContents, Equatable { +public final class TelegramTheme: OrderedItemListEntryContents, Equatable { public let id: Int64 public let accessHash: Int64 public let slug: String @@ -144,27 +144,6 @@ public final class TelegramTheme: Codable, OrderedItemListEntryContents, Equatab self.isDefault = decoder.decodeInt32ForKey("isDefault", orElse: 0) != 0 self.installCount = decoder.decodeOptionalInt32ForKey("installCount") } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: StringCodingKey.self) - - self.id = try container.decode(Int64.self, forKey: "id") - self.accessHash = try container.decode(Int64.self, forKey: "accessHash") - self.slug = try container.decode(String.self, forKey: "slug") - self.title = try container.decode(String.self, forKey: "title") - - if let fileData = try container.decodeIfPresent(Data.self, forKey: "file") { - self.file = TelegramMediaFile(decoder: PostboxDecoder(buffer: MemoryBuffer(data: fileData))) - } else { - self.file = nil - } - - self.settings = try container.decodeIfPresent(TelegramThemeSettings.self, forKey: "settings") - - self.isCreator = (try container.decode(Int32.self, forKey: "isCreator")) != 0 - self.isDefault = (try container.decode(Int32.self, forKey: "isDefault")) != 0 - self.installCount = try container.decodeIfPresent(Int32.self, forKey: "installCount") - } public func encode(_ encoder: PostboxEncoder) { encoder.encodeInt64(self.id, forKey: "id") @@ -189,26 +168,6 @@ public final class TelegramTheme: Codable, OrderedItemListEntryContents, Equatab encoder.encodeNil(forKey: "installCount") } } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: StringCodingKey.self) - - try container.encode(self.id, forKey: "id") - try container.encode(self.accessHash, forKey: "accessHash") - try container.encode(self.slug, forKey: "slug") - try container.encode(self.title, forKey: "title") - if let file = self.file { - let innerEncoder = PostboxEncoder() - file.encode(innerEncoder) - try container.encode(innerEncoder.makeData(), forKey: "file") - } else { - try container.encodeNil(forKey: "file") - } - try container.encodeIfPresent(self.settings, forKey: "settings") - try container.encode((self.isCreator ? 1 : 0) as Int32, forKey: "isCreator") - try container.encode((self.isDefault ? 1 : 0) as Int32, forKey: "isDefault") - try container.encodeIfPresent(self.installCount, forKey: "installCount") - } public static func ==(lhs: TelegramTheme, rhs: TelegramTheme) -> Bool { if lhs.id != rhs.id { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ThemeSettings.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ThemeSettings.swift index 64191262a0..9a28cee8bd 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ThemeSettings.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ThemeSettings.swift @@ -10,13 +10,22 @@ public final class ThemeSettings: Codable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) - self.currentTheme = try container.decodeIfPresent(TelegramTheme.self, forKey: "t") + if let currentThemeData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "t") { + self.currentTheme = TelegramTheme(decoder: PostboxDecoder(buffer: MemoryBuffer(data: currentThemeData.data))) + } else { + self.currentTheme = nil + } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) - try container.encodeIfPresent(self.currentTheme, forKey: "t") + if let currentTheme = self.currentTheme { + let currentThemeData = PostboxEncoder().encodeObjectToRawData(currentTheme) + try container.encode(currentThemeData, forKey: "t") + } else { + try container.encodeNil(forKey: "t") + } } public static func ==(lhs: ThemeSettings, rhs: ThemeSettings) -> Bool { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift index da7e7916af..6364b4514a 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/AccountData/ChangeAccountPhoneNumber.swift @@ -114,6 +114,6 @@ func _internal_requestChangeAccountPhoneNumber(account: Account, phoneNumber: St updatePeers(transaction: transaction, peers: [user], update: { _, updated in return updated }) - } |> mapError { _ -> ChangeAccountPhoneNumberError in return .generic } + } |> mapError { _ -> ChangeAccountPhoneNumberError in } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift index 21ceaf85e8..f12c3b4d16 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift @@ -35,9 +35,9 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .password(password): + case let .password(_, _, _, _, hint, _, _, _, _, _): return account.postbox.transaction { transaction -> Api.auth.LoginToken? in - transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .passwordEntry(hint: password.hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts))) + transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .passwordEntry(hint: hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts))) return nil } |> castError(ExportAuthTransferTokenError.self) @@ -73,9 +73,9 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager mapToSignal { result -> Signal in switch result { - case let .password(password): + case let .password(_, _, _, _, hint, _, _, _, _, _): return updatedAccount.postbox.transaction { transaction -> Api.auth.LoginToken? in - transaction.setState(UnauthorizedAccountState(isTestingEnvironment: updatedAccount.testingEnvironment, masterDatacenterId: updatedAccount.masterDatacenterId, contents: .passwordEntry(hint: password.hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts))) + transaction.setState(UnauthorizedAccountState(isTestingEnvironment: updatedAccount.testingEnvironment, masterDatacenterId: updatedAccount.masterDatacenterId, contents: .passwordEntry(hint: hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts))) return nil } |> castError(ExportAuthTransferTokenError.self) @@ -130,7 +130,7 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager castError(ExportAuthTransferTokenError.self) |> switchToLatest - case let .authorizationSignUpRequired: + case .authorizationSignUpRequired: return .fail(.generic) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift index ff04a4c1c0..c87dd353b5 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift @@ -15,11 +15,11 @@ func _internal_twoStepVerificationConfiguration(account: Account) -> Signal retryRequest |> map { result -> TwoStepVerificationConfiguration in switch result { - case let .password(password): - if password.currentAlgo != nil { - return .set(hint: password.hint ?? "", hasRecoveryEmail: (password.flags & (1 << 0)) != 0, pendingEmail: password.emailUnconfirmedPattern.flatMap({ TwoStepVerificationPendingEmail(pattern: $0, codeLength: nil) }), hasSecureValues: (password.flags & (1 << 1)) != 0, pendingResetTimestamp: password.pendingResetDate) + case let .password(flags, currentAlgo, _, _, hint, emailUnconfirmedPattern, _, _, _, pendingResetDate): + if currentAlgo != nil { + return .set(hint: hint ?? "", hasRecoveryEmail: (flags & (1 << 0)) != 0, pendingEmail: emailUnconfirmedPattern.flatMap({ TwoStepVerificationPendingEmail(pattern: $0, codeLength: nil) }), hasSecureValues: (flags & (1 << 1)) != 0, pendingResetTimestamp: pendingResetDate) } else { - return .notSet(pendingEmail: password.emailUnconfirmedPattern.flatMap({ TwoStepVerificationPendingEmail(pattern: $0, codeLength: nil) })) + return .notSet(pendingEmail: emailUnconfirmedPattern.flatMap({ TwoStepVerificationPendingEmail(pattern: $0, codeLength: nil) })) } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift index 74ab3af05c..98a2b5f991 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/ContactManagement.swift @@ -5,7 +5,9 @@ import SwiftSignalKit import CryptoUtils private func md5(_ data: Data) -> Data { - return data.withUnsafeBytes { bytes -> Data in + return data.withUnsafeBytes { rawBytes -> Data in + let bytes = rawBytes.baseAddress! + return CryptoMD5(bytes, Int32(data.count)) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift index 471faaa5ba..6daaab4baa 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Contacts/UpdateContactName.swift @@ -24,6 +24,6 @@ func _internal_updateContactName(account: Account, peerId: PeerId, firstName: St return .fail(.generic) } } - |> mapError { _ -> UpdateContactNameError in return .generic } + |> mapError { _ -> UpdateContactNameError in } |> switchToLatest } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Data/Configuration.swift b/submodules/TelegramCore/Sources/TelegramEngine/Data/Configuration.swift index 48f702ccad..d196aa0f54 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Data/Configuration.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Data/Configuration.swift @@ -83,7 +83,7 @@ public extension TelegramEngine.EngineData.Item { guard let view = view as? PreferencesView else { preconditionFailure() } - guard let limitsConfiguration = view.values[PreferencesKeys.limitsConfiguration] as? LimitsConfiguration else { + guard let limitsConfiguration = view.values[PreferencesKeys.limitsConfiguration]?.get(LimitsConfiguration.self) else { return EngineConfiguration.Limits(LimitsConfiguration.defaultValue) } return EngineConfiguration.Limits(limitsConfiguration) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/LocalizationInfo.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/LocalizationInfo.swift index cc0332797b..838c889580 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/LocalizationInfo.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/LocalizationInfo.swift @@ -6,8 +6,8 @@ import TelegramApi extension LocalizationInfo { init(apiLanguage: Api.LangPackLanguage) { switch apiLanguage { - case let .langPackLanguage(language): - self.init(languageCode: language.langCode, baseLanguageCode: language.baseLangCode, customPluralizationCode: language.pluralCode, title: language.name, localizedTitle: language.nativeName, isOfficial: (language.flags & (1 << 0)) != 0, totalStringCount: language.stringsCount, translatedStringCount: language.translatedCount, platformUrl: language.translationsUrl) + case let .langPackLanguage(flags, name, nativeName, langCode, baseLangCode, pluralCode, stringsCount, translatedCount, translationsUrl): + self.init(languageCode: langCode, baseLanguageCode: baseLangCode, customPluralizationCode: pluralCode, title: name, localizedTitle: nativeName, isOfficial: (flags & (1 << 0)) != 0, totalStringCount: stringsCount, translatedStringCount: translatedCount, platformUrl: translationsUrl) } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift index 172f3e09f0..a2533fb7c7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift @@ -9,8 +9,8 @@ func _internal_currentlySuggestedLocalization(network: Network, extractKeys: [St |> retryRequest |> mapToSignal { result -> Signal in switch result { - case let .config(config): - if let suggestedLangCode = config.suggestedLangCode { + case let .config(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, suggestedLangCode, _, _): + if let suggestedLangCode = suggestedLangCode { return _internal_suggestedLocalizationInfo(network: network, languageCode: suggestedLangCode, extractKeys: extractKeys) |> map(Optional.init) } else { return .single(nil) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ChatList.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ChatList.swift index bf2a88a5e6..5023bcdef8 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ChatList.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ChatList.swift @@ -116,7 +116,7 @@ public extension EngineChatList.Group { extension EngineChatList.Item { convenience init?(_ entry: ChatListEntry) { switch entry { - case let .MessageEntry(index, messages, readState, isRemovedFromTotalUnreadCount, embeddedInterfaceState, renderedPeer, presence, summaryInfo, hasFailed, isContact): + case let .MessageEntry(index, messages, readState, isRemovedFromTotalUnreadCount, _, renderedPeer, presence, summaryInfo, hasFailed, isContact): self.init( index: index, messages: messages.map(EngineMessage.init), diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift index 66c64fce1e..2be0e7f592 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/ExportMessageLink.swift @@ -5,7 +5,7 @@ import SwiftSignalKit func _internal_exportMessageLink(account: Account, peerId: PeerId, messageId: MessageId, isThread: Bool = false) -> Signal { return account.postbox.transaction { transaction -> (Peer, MessageId)? in - var peer: Peer? = transaction.getPeer(messageId.peerId) + let peer: Peer? = transaction.getPeer(messageId.peerId) if let peer = peer { return (peer, messageId) } else { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/OutgoingMessageWithChatContextResult.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/OutgoingMessageWithChatContextResult.swift index 983c0ecc2e..16ab23533f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/OutgoingMessageWithChatContextResult.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/OutgoingMessageWithChatContextResult.swift @@ -132,7 +132,7 @@ private func outgoingMessageWithChatContextResult(to peerId: PeerId, results: Ch return .message(text: caption, attributes: attributes, mediaReference: nil, replyToMessageId: replyToMessageId, localGroupingKey: nil, correlationId: correlationId) } } - case let .text(text, entities, disableUrlPreview, replyMarkup): + case let .text(text, entities, _, replyMarkup): if let entities = entities { attributes.append(entities) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift index e8edd1a520..2f95cd54c3 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift @@ -31,7 +31,7 @@ func _internal_requestMessageSelectPollOption(account: Account, messageId: Messa resultPoll = transaction.getMedia(pollId) as? TelegramMediaPoll if let poll = poll { switch poll { - case let .poll(id, flags, question, answers, closePeriod, _): + case let .poll(_, flags, question, answers, closePeriod, _): let publicity: TelegramMediaPollPublicity if (flags & (1 << 1)) != 0 { publicity = .public @@ -45,15 +45,13 @@ func _internal_requestMessageSelectPollOption(account: Account, messageId: Messa kind = .poll(multipleAnswers: (flags & (1 << 2)) != 0) } resultPoll = TelegramMediaPoll(pollId: pollId, publicity: publicity, kind: kind, text: question, options: answers.map(TelegramMediaPollOption.init(apiOption:)), correctAnswers: nil, results: TelegramMediaPollResults(apiResults: results), isClosed: (flags & (1 << 0)) != 0, deadlineTimeout: closePeriod) - default: - break } } let resultsMin: Bool switch results { - case let .pollResults(pollResults): - resultsMin = (pollResults.flags & (1 << 0)) != 0 + case let .pollResults(flags, _, _, _, _, _): + resultsMin = (flags & (1 << 0)) != 0 } resultPoll = resultPoll?.withUpdatedResults(TelegramMediaPollResults(apiResults: results), min: resultsMin) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift index 477ccd8f14..14f865ad8f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift @@ -115,7 +115,7 @@ func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId } if let (latitude, longitude) = location { flags |= (1 << 0) - var geoPointFlags: Int32 = 0 + let geoPointFlags: Int32 = 0 geoPoint = Api.InputGeoPoint.inputGeoPoint(flags: geoPointFlags, lat: latitude, long: longitude, accuracyRadius: nil) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift index 82f3cf7ae4..e26a6025b3 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestStartBot.swift @@ -44,7 +44,7 @@ func _internal_requestStartBotInGroup(account: Account, botPeerId: PeerId, group return account.postbox.transaction { transaction -> (Peer?, Peer?) in return (transaction.getPeer(botPeerId), transaction.getPeer(groupPeerId)) } - |> mapError { _ -> RequestStartBotInGroupError in return .generic } + |> mapError { _ -> RequestStartBotInGroupError in } |> mapToSignal { botPeer, groupPeer -> Signal in if let botPeer = botPeer, let inputUser = apiInputUser(botPeer), let groupPeer = groupPeer, let inputGroup = apiInputPeer(groupPeer) { let request = account.network.request(Api.functions.messages.startBot(bot: inputUser, peer: inputGroup, randomId: Int64.random(in: Int64.min ... Int64.max), startParam: payload ?? "")) @@ -55,8 +55,7 @@ func _internal_requestStartBotInGroup(account: Account, botPeerId: PeerId, group account.stateManager.addUpdates(result) if groupPeerId.namespace == Namespaces.Peer.CloudChannel { return _internal_fetchChannelParticipant(account: account, peerId: groupPeerId, participantId: botPeerId) - |> mapError { _ -> RequestStartBotInGroupError in return .generic - } + |> mapError { _ -> RequestStartBotInGroupError in } |> mapToSignal { participant -> Signal in return account.postbox.transaction { transaction -> StartBotInGroupResult in if let participant = participant, let peer = transaction.getPeer(participant.peerId) { @@ -69,8 +68,7 @@ func _internal_requestStartBotInGroup(account: Account, botPeerId: PeerId, group return .none } } - |> mapError { _ -> RequestStartBotInGroupError in return .generic - } + |> mapError { _ -> RequestStartBotInGroupError in } } } else { return .single(.none) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift index 282b3f5686..8e9b879f1f 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/SearchMessages.swift @@ -458,7 +458,6 @@ func _internal_downloadMessage(postbox: Postbox, network: Network, messageId: Me } } |> `catch` { _ -> Signal in - return .single(nil) } } } @@ -557,7 +556,6 @@ func fetchRemoteMessage(postbox: Postbox, source: FetchMessageHistoryHoleSource, } } |> `catch` { _ -> Signal in - return .single(nil) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift index 621263a476..d50898bcd2 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/UpdatePinnedMessage.swift @@ -19,7 +19,6 @@ func _internal_requestUpdatePinnedMessage(account: Account, peerId: PeerId, upda return (transaction.getPeer(peerId), transaction.getPeerCachedData(peerId: peerId)) } |> mapError { _ -> UpdatePinnedMessageError in - return .generic } |> mapToSignal { peer, cachedPeerData -> Signal in guard let peer = peer, let inputPeer = apiInputPeer(peer) else { @@ -105,7 +104,6 @@ func _internal_requestUpdatePinnedMessage(account: Account, peerId: PeerId, upda } } |> mapError { _ -> UpdatePinnedMessageError in - return .generic } } } @@ -116,7 +114,6 @@ func _internal_requestUnpinAllMessages(account: Account, peerId: PeerId) -> Sign return (transaction.getPeer(peerId), transaction.getPeerCachedData(peerId: peerId)) } |> mapError { _ -> UpdatePinnedMessageError in - return .generic } |> mapToSignal { peer, cachedPeerData -> Signal in guard let peer = peer, let inputPeer = apiInputPeer(peer) else { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift index 8c50af3d59..2ec581e49c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Payments/BotPaymentForm.swift @@ -477,7 +477,7 @@ func _internal_requestBotPaymentReceipt(account: Account, messageId: MessageId) |> mapToSignal { result -> Signal in return account.postbox.transaction { transaction -> BotPaymentReceipt in switch result { - case let .paymentReceipt(flags, date, botId, providerId, title, description, photo, invoice, info, shipping, tipAmount, currency, totalAmount, credentialsTitle, users): + case let .paymentReceipt(_, _, botId, _, title, description, photo, invoice, info, shipping, tipAmount, currency, totalAmount, credentialsTitle, users): var peers: [Peer] = [] for user in users { peers.append(TelegramUser(user: user)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift index 9df47f95f4..1e5cdb1a5e 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChannelOwnershipTransfer.swift @@ -77,8 +77,7 @@ func _internal_updateChannelOwnership(account: Account, accountStateManager: Acc } return combineLatest(_internal_fetchChannelParticipant(account: account, peerId: channelId, participantId: account.peerId), _internal_fetchChannelParticipant(account: account, peerId: channelId, participantId: memberId)) - |> mapError { error -> ChannelOwnershipTransferError in - return .generic + |> mapError { _ -> ChannelOwnershipTransferError in } |> mapToSignal { currentCreator, currentParticipant -> Signal<[(ChannelParticipant?, RenderedChannelParticipant)], ChannelOwnershipTransferError> in return account.postbox.transaction { transaction -> Signal<[(ChannelParticipant?, RenderedChannelParticipant)], ChannelOwnershipTransferError> in @@ -185,14 +184,14 @@ func _internal_updateChannelOwnership(account: Account, accountStateManager: Acc } return [(currentCreator, RenderedChannelParticipant(participant: updatedPreviousCreator, peer: accountUser, peers: peers, presences: presences)), (currentParticipant, RenderedChannelParticipant(participant: updatedParticipant, peer: user, peers: peers, presences: presences))] } - |> mapError { _ -> ChannelOwnershipTransferError in return .generic } + |> mapError { _ -> ChannelOwnershipTransferError in } } } } else { return .fail(.generic) } } - |> mapError { _ -> ChannelOwnershipTransferError in return .generic } + |> mapError { _ -> ChannelOwnershipTransferError in } |> switchToLatest } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift index ad610f577f..729ee284da 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ChatListFiltering.swift @@ -277,9 +277,9 @@ public struct ChatListFilter: Codable, Equatable { try container.encodeIfPresent(self.emoticon, forKey: "emoticon") try container.encode(self.data.categories.rawValue, forKey: "categories") - try container.encode(self.data.excludeMuted ? 1 : 0, forKey: "excludeMuted") - try container.encode(self.data.excludeRead ? 1 : 0, forKey: "excludeRead") - try container.encode(self.data.excludeArchived ? 1 : 0, forKey: "excludeArchived") + try container.encode((self.data.excludeMuted ? 1 : 0) as Int32, forKey: "excludeMuted") + try container.encode((self.data.excludeRead ? 1 : 0) as Int32, forKey: "excludeRead") + try container.encode((self.data.excludeArchived ? 1 : 0) as Int32, forKey: "excludeArchived") try container.encode(self.data.includePeers.peers.map { $0.toInt64() }, forKey: "includePeers") try container.encode(self.data.includePeers.pinnedPeers.map { $0.toInt64() }, forKey: "pinnedPeers") try container.encode(self.data.excludePeers.map { $0.toInt64() }, forKey: "excludePeers") diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ConvertGroupToSupergroup.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ConvertGroupToSupergroup.swift index 26f89f9310..f126fde254 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ConvertGroupToSupergroup.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ConvertGroupToSupergroup.swift @@ -39,7 +39,6 @@ func _internal_convertGroupToSupergroup(account: Account, peerId: PeerId) -> Sig return createdPeerId } |> mapError { _ -> ConvertGroupToSupergroupError in - return .generic } |> timeout(5.0, queue: Queue.concurrentDefaultQueue(), alternate: .fail(.generic)) } @@ -64,6 +63,6 @@ public func convertGroupToGigagroup(account: Account, peerId: PeerId) -> Signal< return .complete() } } - |> mapError { _ -> ConvertGroupToGigagroupError in return .generic } + |> mapError { _ -> ConvertGroupToGigagroupError in } |> switchToLatest } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateSecretChat.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateSecretChat.swift index 7d57209fb7..5a909d36b8 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateSecretChat.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/CreateSecretChat.swift @@ -13,7 +13,7 @@ func _internal_createSecretChat(account: Account, peerId: PeerId) -> Signal Signal in if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) { return validatedEncryptionConfig(postbox: account.postbox, network: account.network) - |> mapError { _ -> CreateSecretChatError in return .generic } + |> mapError { _ -> CreateSecretChatError in } |> mapToSignal { config -> Signal in let aBytes = malloc(256)! let _ = SecRandomCopyBytes(nil, 256, aBytes.assumingMemoryBound(to: UInt8.self)) @@ -43,11 +43,11 @@ func _internal_createSecretChat(account: Account, peerId: PeerId) -> Signal mapError { _ -> CreateSecretChatError in return .generic } + } |> mapError { _ -> CreateSecretChatError in } } } } else { return .fail(.generic) } - } |> mapError { _ -> CreateSecretChatError in return .generic } |> switchToLatest + } |> mapError { _ -> CreateSecretChatError in } |> switchToLatest } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift index 718fd44925..da0d646349 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InactiveChannels.swift @@ -24,16 +24,16 @@ func _internal_inactiveChannelList(network: Network) -> Signal<[InactiveChannel] |> retryRequest |> map { result in switch result { - case let .inactiveChats(dates, chats, users): + case let .inactiveChats(dates, chats, _): let channels = chats.compactMap { parseTelegramGroupOrChannel(chat: $0) } var participantsCounts: [PeerId: Int32] = [:] for chat in chats { switch chat { - case let .channel(channel): - if let participantsCountValue = channel.participantsCount { - participantsCounts[chat.peerId] = channel.participantsCount + case let .channel(_, _, _, _, _, _, _, _, _, _, _, participantsCountValue): + if let participantsCountValue = participantsCountValue { + participantsCounts[chat.peerId] = participantsCountValue } default: break diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift index e7ce8e3463..115e641426 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift @@ -109,7 +109,7 @@ func _internal_editPeerExportedInvitation(account: Account, peerId: PeerId, link } else { return nil } - } |> mapError { _ in .generic } + } |> mapError { _ -> EditPeerExportedInvitationError in } } } else { return .complete() @@ -179,7 +179,7 @@ func _internal_revokePeerExportedInvitation(account: Account, peerId: PeerId, li } else { return nil } - } |> mapError { _ in .generic } + } |> mapError { _ -> RevokePeerExportedInvitationError in } } } else { return .complete() diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift index deb87d78ed..2f20cf0c0c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/JoinLink.swift @@ -67,9 +67,9 @@ func _internal_joinLinkInformation(_ hash: String, account: Account) -> Signal mapToSignal { (result) -> Signal in if let result = result { switch result { - case let .chatInvite(invite): - let photo = telegramMediaImageFromApiPhoto(invite.photo).flatMap({ smallestImageRepresentation($0.representations) }) - return .single(.invite(title: invite.title, photoRepresentation: photo, participantsCount: invite.participantsCount, participants: invite.participants?.map({TelegramUser(user: $0)}))) + case let .chatInvite(_, title, invitePhoto, participantsCount, participants): + let photo = telegramMediaImageFromApiPhoto(invitePhoto).flatMap({ smallestImageRepresentation($0.representations) }) + return .single(.invite(title: title, photoRepresentation: photo, participantsCount: participantsCount, participants: participants?.map({TelegramUser(user: $0)}))) case let .chatInviteAlready(chat): if let peer = parseTelegramGroupOrChannel(chat: chat) { return account.postbox.transaction({ (transaction) -> ExternalJoiningChatState in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift index f905aae793..8f6a35ba9e 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ManageChannelDiscussionGroup.swift @@ -42,7 +42,7 @@ func _internal_updateGroupDiscussionForChannel(network: Network, postbox: Postbo return postbox.transaction { transaction -> (channel: Peer?, group: Peer?) in return (channel: channelId.flatMap(transaction.getPeer), group: groupId.flatMap(transaction.getPeer)) } - |> mapError { _ in ChannelDiscussionGroupError.generic } + |> mapError { _ -> ChannelDiscussionGroupError in } |> mapToSignal { channel, group -> Signal in let apiChannel = channel.flatMap(apiInputChannel) ?? Api.InputChannel.inputChannelEmpty let apiGroup = group.flatMap(apiInputChannel) ?? Api.InputChannel.inputChannelEmpty diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift index f5888f1e09..9e5d775178 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/PeerPhotoUpdater.swift @@ -72,7 +72,7 @@ func _internal_updatePeerPhoto(postbox: Postbox, network: Network, stateManager: func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, stateManager: AccountStateManager?, accountPeerId: PeerId, peer: Signal, photo: Signal?, video: Signal?, videoStartTimestamp: Double?, mapResourceToAvatarSizes: @escaping (MediaResource, [TelegramMediaImageRepresentation]) -> Signal<[Int: Data], NoError>) -> Signal { return peer - |> mapError { _ in return .generic } + |> mapError { _ -> UploadPeerPhotoError in } |> mapToSignal { peer -> Signal in if let photo = photo { let mappedPhoto = photo @@ -99,7 +99,7 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state } return combineLatest(mappedPhoto, mappedVideo) - |> mapError { _ -> UploadPeerPhotoError in return .generic } + |> mapError { _ -> UploadPeerPhotoError in } |> mapToSignal { photoResult, videoResult -> Signal<(UpdatePeerPhotoStatus, MediaResource?, MediaResource?), UploadPeerPhotoError> in switch photoResult.content { case .error: @@ -200,7 +200,7 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state }) } return (.complete(representations), photoResult.resource, videoResult?.resource) - } |> mapError {_ in return UploadPeerPhotoError.generic} + } |> mapError { _ -> UploadPeerPhotoError in } } } else { var flags: Int32 = (1 << 0) @@ -248,7 +248,7 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state }) return (.complete(groupOrChannel.profileImageRepresentations), photoResult.resource, videoResult?.resource) } - |> mapError { _ in return .generic } + |> mapError { _ -> UploadPeerPhotoError in } } } } @@ -322,7 +322,7 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state }) return .complete(groupOrChannel.profileImageRepresentations) } - |> mapError { _ in return .generic } + |> mapError { _ -> UploadPeerPhotoError in } } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift index 0463c673b2..4e430287c1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RequestUserPhotos.swift @@ -40,12 +40,12 @@ func _internal_requestPeerPhotos(postbox: Postbox, network: Network, peerId: Pee let totalCount:Int let photos: [Api.Photo] switch result { - case let .photos(data): - photos = data.photos + case let .photos(photosValue, _): + photos = photosValue totalCount = photos.count - case let .photosSlice(data): - photos = data.photos - totalCount = Int(data.count) + case let .photosSlice(count, photosValue, _): + photos = photosValue + totalCount = Int(count) } var images: [TelegramPeerPhoto] = [] diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift index d01b5d46fc..c6bc6cd994 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/SearchPeers.swift @@ -44,8 +44,8 @@ func _internal_searchPeers(account: Account, query: String) -> Signal<([FoundPee peers[groupOrChannel.id] = groupOrChannel switch chat { /*feed*/ - case let .channel(channel): - if let participantsCount = channel.participantsCount { + case let .channel(_, _, _, _, _, _, _, _, _, _, _, participantsCount): + if let participantsCount = participantsCount { subscribers[groupOrChannel.id] = participantsCount } default: diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/TogglePeerChatPinned.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/TogglePeerChatPinned.swift index b9fb6232b4..46cb72da73 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/TogglePeerChatPinned.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/TogglePeerChatPinned.swift @@ -37,7 +37,7 @@ func _internal_toggleItemPinned(postbox: Postbox, location: TogglePeerChatPinned additionalCount = 1 } - let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue let limitCount: Int if case .root = groupId { limitCount = Int(limitsConfiguration.maxPinnedChatCount) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift index a2bfc8fc3c..5a0c0c34a7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdateCachedPeerData.swift @@ -171,15 +171,15 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee |> mapToSignal { result -> Signal in return postbox.transaction { transaction -> Bool in switch result { - case let .userFull(userFull): - if let telegramUser = TelegramUser.merge(transaction.getPeer(userFull.user.peerId) as? TelegramUser, rhs: userFull.user) { + case let .userFull(_, userFullUser, _, _, _, userFullNotifySettings, _, _, _, _, _, _): + if let telegramUser = TelegramUser.merge(transaction.getPeer(userFullUser.peerId) as? TelegramUser, rhs: userFullUser) { updatePeers(transaction: transaction, peers: [telegramUser], update: { _, updated -> Peer in return updated }) } - transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: userFull.notifySettings)]) - if let presence = TelegramUserPresence(apiUser: userFull.user) { - updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: [userFull.user.peerId: presence]) + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: userFullNotifySettings)]) + if let presence = TelegramUserPresence(apiUser: userFullUser) { + updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: [userFullUser.peerId: presence]) } } transaction.updatePeerCachedData(peerIds: [peerId], update: { peerId, current in @@ -190,27 +190,25 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee previous = CachedUserData() } switch result { - case let .userFull(userFull): - let botInfo = userFull.botInfo.flatMap(BotInfo.init(apiBotInfo:)) - let isBlocked = (userFull.flags & (1 << 0)) != 0 - let voiceCallsAvailable = (userFull.flags & (1 << 4)) != 0 - var videoCallsAvailable = (userFull.flags & (1 << 13)) != 0 - #if DEBUG - videoCallsAvailable = true - #endif - let callsPrivate = (userFull.flags & (1 << 5)) != 0 - let canPinMessages = (userFull.flags & (1 << 7)) != 0 - let pinnedMessageId = userFull.pinnedMsgId.flatMap({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }) + case let .userFull(userFullFlags, _, userFullAbout, userFullSettings, _, _, userFullBotInfo, userFullPinnedMsgId, userFullCommonChatsCount, _, userFullTtlPeriod, userFullThemeEmoticon): + let botInfo = userFullBotInfo.flatMap(BotInfo.init(apiBotInfo:)) + let isBlocked = (userFullFlags & (1 << 0)) != 0 + let voiceCallsAvailable = (userFullFlags & (1 << 4)) != 0 + let videoCallsAvailable = (userFullFlags & (1 << 13)) != 0 + + let callsPrivate = (userFullFlags & (1 << 5)) != 0 + let canPinMessages = (userFullFlags & (1 << 7)) != 0 + let pinnedMessageId = userFullPinnedMsgId.flatMap({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }) - let peerStatusSettings = PeerStatusSettings(apiSettings: userFull.settings) + let peerStatusSettings = PeerStatusSettings(apiSettings: userFullSettings) - let hasScheduledMessages = (userFull.flags & 1 << 12) != 0 + let hasScheduledMessages = (userFullFlags & 1 << 12) != 0 - let autoremoveTimeout: CachedPeerAutoremoveTimeout = .known(CachedPeerAutoremoveTimeout.Value(userFull.ttlPeriod)) + let autoremoveTimeout: CachedPeerAutoremoveTimeout = .known(CachedPeerAutoremoveTimeout.Value(userFullTtlPeriod)) - return previous.withUpdatedAbout(userFull.about).withUpdatedBotInfo(botInfo).withUpdatedCommonGroupCount(userFull.commonChatsCount).withUpdatedIsBlocked(isBlocked).withUpdatedVoiceCallsAvailable(voiceCallsAvailable).withUpdatedVideoCallsAvailable(videoCallsAvailable).withUpdatedCallsPrivate(callsPrivate).withUpdatedCanPinMessages(canPinMessages).withUpdatedPeerStatusSettings(peerStatusSettings).withUpdatedPinnedMessageId(pinnedMessageId).withUpdatedHasScheduledMessages(hasScheduledMessages) + return previous.withUpdatedAbout(userFullAbout).withUpdatedBotInfo(botInfo).withUpdatedCommonGroupCount(userFullCommonChatsCount).withUpdatedIsBlocked(isBlocked).withUpdatedVoiceCallsAvailable(voiceCallsAvailable).withUpdatedVideoCallsAvailable(videoCallsAvailable).withUpdatedCallsPrivate(callsPrivate).withUpdatedCanPinMessages(canPinMessages).withUpdatedPeerStatusSettings(peerStatusSettings).withUpdatedPinnedMessageId(pinnedMessageId).withUpdatedHasScheduledMessages(hasScheduledMessages) .withUpdatedAutoremoveTimeout(autoremoveTimeout) - .withUpdatedThemeEmoticon(userFull.themeEmoticon) + .withUpdatedThemeEmoticon(userFullThemeEmoticon) } }) return true @@ -224,16 +222,16 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee switch result { case let .chatFull(fullChat, chats, users): switch fullChat { - case let .chatFull(chatFull): - transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: chatFull.notifySettings)]) + case let .chatFull(_, _, _, _, _, notifySettings, _, _, _, _, _, _, _, _): + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) case .channelFull: break } switch fullChat { - case let .chatFull(chatFull): + case let .chatFull(chatFullFlags, _, chatFullAbout, chatFullParticipants, chatFullChatPhoto, _, chatFullExportedInvite, chatFullBotInfo, chatFullPinnedMsgId, _, chatFullCall, _, chatFullGroupcallDefaultJoinAs, chatFullThemeEmoticon): var botInfos: [CachedPeerBotInfo] = [] - for botInfo in chatFull.botInfo ?? [] { + for botInfo in chatFullBotInfo ?? [] { switch botInfo { case let .botInfo(userId, _, _): let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId)) @@ -241,7 +239,7 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee botInfos.append(CachedPeerBotInfo(peerId: peerId, botInfo: parsedBotInfo)) } } - let participants = CachedGroupParticipants(apiParticipants: chatFull.participants) + let participants = CachedGroupParticipants(apiParticipants: chatFullParticipants) var invitedBy: PeerId? if let participants = participants { @@ -255,10 +253,10 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee } } - let photo: TelegramMediaImage? = chatFull.chatPhoto.flatMap(telegramMediaImageFromApiPhoto) + let photo: TelegramMediaImage? = chatFullChatPhoto.flatMap(telegramMediaImageFromApiPhoto) - let exportedInvitation = chatFull.exportedInvite.flatMap { ExportedInvitation(apiExportedInvite: $0) } - let pinnedMessageId = chatFull.pinnedMsgId.flatMap({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }) + let exportedInvitation = chatFullExportedInvite.flatMap { ExportedInvitation(apiExportedInvite: $0) } + let pinnedMessageId = chatFullPinnedMsgId.flatMap({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }) var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] @@ -283,16 +281,16 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences) var flags = CachedGroupFlags() - if (chatFull.flags & 1 << 7) != 0 { + if (chatFullFlags & 1 << 7) != 0 { flags.insert(.canChangeUsername) } var hasScheduledMessages = false - if (chatFull.flags & 1 << 8) != 0 { + if (chatFullFlags & 1 << 8) != 0 { hasScheduledMessages = true } - let groupCallDefaultJoinAs = chatFull.groupcallDefaultJoinAs + let groupCallDefaultJoinAs = chatFullGroupcallDefaultJoinAs transaction.updatePeerCachedData(peerIds: [peerId], update: { _, current in let previous: CachedGroupData @@ -303,7 +301,7 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee } var updatedActiveCall: CachedChannelData.ActiveCall? - if let inputCall = chatFull.call { + if let inputCall = chatFullCall { switch inputCall { case let .inputGroupCall(id, accessHash): updatedActiveCall = CachedChannelData.ActiveCall(id: id, accessHash: accessHash, title: previous.activeCall?.title, scheduleTimestamp: previous.activeCall?.scheduleTimestamp, subscribedToScheduled: previous.activeCall?.subscribedToScheduled ?? false) @@ -314,14 +312,14 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee .withUpdatedExportedInvitation(exportedInvitation) .withUpdatedBotInfos(botInfos) .withUpdatedPinnedMessageId(pinnedMessageId) - .withUpdatedAbout(chatFull.about) + .withUpdatedAbout(chatFullAbout) .withUpdatedFlags(flags) .withUpdatedHasScheduledMessages(hasScheduledMessages) .withUpdatedInvitedBy(invitedBy) .withUpdatedPhoto(photo) .withUpdatedActiveCall(updatedActiveCall) .withUpdatedCallJoinPeerId(groupCallDefaultJoinAs?.peerId) - .withUpdatedThemeEmoticon(chatFull.themeEmoticon) + .withUpdatedThemeEmoticon(chatFullThemeEmoticon) }) case .channelFull: break @@ -352,14 +350,14 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee switch result { case let .chatFull(fullChat, chats, users): switch fullChat { - case let .channelFull(channelFull): - transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: channelFull.notifySettings)]) + case let .channelFull(_, _, _, _, _, _, _, _, _, _, _, _, notifySettings, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _): + transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)]) case .chatFull: break } switch fullChat { - case let .channelFull(flags, _, about, participantsCount, adminsCount, kickedCount, bannedCount, _, _, _, _, chatPhoto, _, apiExportedInvite, apiBotInfos, migratedFromChatId, migratedFromMaxId, pinnedMsgId, stickerSet, minAvailableMsgId, folderId, linkedChatId, location, slowmodeSeconds, slowmodeNextSendDate, statsDc, pts, inputCall, ttl, pendingSuggestions, groupcallDefaultJoinAs, themeEmoticon): + case let .channelFull(flags, _, about, participantsCount, adminsCount, kickedCount, bannedCount, _, _, _, _, chatPhoto, _, apiExportedInvite, apiBotInfos, migratedFromChatId, migratedFromMaxId, pinnedMsgId, stickerSet, minAvailableMsgId, _, linkedChatId, location, slowmodeSeconds, slowmodeNextSendDate, statsDc, _, inputCall, ttl, pendingSuggestions, groupcallDefaultJoinAs, themeEmoticon): var channelFlags = CachedChannelFlags() if (flags & (1 << 3)) != 0 { channelFlags.insert(.canDisplayParticipants) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift index 27bacc080f..47935d495e 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/UpdatePeerInfo.swift @@ -42,7 +42,7 @@ func _internal_updatePeerTitle(account: Account, peerId: PeerId, title: String) return updated }) } - } |> mapError { _ -> UpdatePeerTitleError in return .generic } + } |> mapError { _ -> UpdatePeerTitleError in } } } else { return .fail(.generic) @@ -50,7 +50,7 @@ func _internal_updatePeerTitle(account: Account, peerId: PeerId, title: String) } else { return .fail(.generic) } - } |> mapError { _ -> UpdatePeerTitleError in return .generic } |> switchToLatest + } |> mapError { _ -> UpdatePeerTitleError in } |> switchToLatest } public enum UpdatePeerDescriptionError { @@ -79,7 +79,7 @@ func _internal_updatePeerDescription(account: Account, peerId: PeerId, descripti }) } } - |> mapError { _ -> UpdatePeerDescriptionError in return .generic } + |> mapError { _ -> UpdatePeerDescriptionError in } } } else { return .fail(.generic) @@ -87,5 +87,5 @@ func _internal_updatePeerDescription(account: Account, peerId: PeerId, descripti } else { return .fail(.generic) } - } |> mapError { _ -> UpdatePeerDescriptionError in return .generic } |> switchToLatest + } |> mapError { _ -> UpdatePeerDescriptionError in } |> switchToLatest } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift index b9ec6fbb66..5fc712fd8c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Privacy/UpdatedAccountPrivacySettings.swift @@ -106,8 +106,8 @@ func _internal_requestAccountPrivacySettings(account: Account) -> Signal Signal { - var initialState = CacheUsageStatsState() + let initialState = CacheUsageStatsState() if let peerId = peerId { initialState.lowerBound = MessageIndex.lowerBound(peerId: peerId) initialState.upperBound = MessageIndex.upperBound(peerId: peerId) @@ -75,7 +75,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a let fetch = account.postbox.transaction { transaction -> ([PeerId : Set], [MediaId : Media], MessageIndex?) in return transaction.enumerateMedia(lowerBound: state.with { $0.lowerBound }, upperBound: state.with { $0.upperBound }, limit: 1000) } - |> mapError { _ -> CollectCacheUsageStatsError in preconditionFailure() } + |> mapError { _ -> CollectCacheUsageStatsError in } let process: ([PeerId : Set], [MediaId : Media], MessageIndex?) -> Signal = { mediaByPeer, mediaRefs, updatedLowerBound in var mediaIdToPeerId: [MediaId: PeerId] = [:] @@ -141,7 +141,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a } } return account.postbox.mediaBox.collectResourceCacheUsage(resourceIds) - |> mapError { _ -> CollectCacheUsageStatsError in preconditionFailure() } + |> mapError { _ -> CollectCacheUsageStatsError in } |> mapToSignal { result -> Signal in state.with { state -> Void in state.lowerBound = updatedLowerBound @@ -171,7 +171,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a } if updatedLowerBound == nil { if peerId != nil { - let (finalMedia, finalMediaResourceIds, allResourceIds) = state.with { state -> ([PeerId: [PeerCacheUsageCategory: [MediaId: Int64]]], [MediaId: [MediaResourceId]], Set) in + let (finalMedia, finalMediaResourceIds, _) = state.with { state -> ([PeerId: [PeerCacheUsageCategory: [MediaId: Int64]]], [MediaId: [MediaResourceId]], Set) in return (state.media, state.mediaResourceIds, state.allResourceIds) } return account.postbox.transaction { transaction -> CacheUsageStats in @@ -185,7 +185,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a } } return CacheUsageStats(media: finalMedia, mediaResourceIds: finalMediaResourceIds, peers: peers, otherSize: 0, otherPaths: [], cacheSize: 0, tempPaths: [], tempSize: 0, immutableSize: 0) - } |> mapError { _ -> CollectCacheUsageStatsError in preconditionFailure() } + } |> mapError { _ -> CollectCacheUsageStatsError in } |> mapToSignal { stats -> Signal in return .fail(.done(stats)) } @@ -196,7 +196,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a } return account.postbox.mediaBox.collectOtherResourceUsage(excludeIds: excludeResourceIds, combinedExcludeIds: allResourceIds.union(excludeResourceIds)) - |> mapError { _ in return CollectCacheUsageStatsError.generic } + |> mapError { _ -> CollectCacheUsageStatsError in } |> mapToSignal { otherSize, otherPaths, cacheSize in var tempPaths: [String] = [] var tempSize: Int64 = 0 @@ -264,7 +264,7 @@ func _internal_collectCacheUsageStats(account: Account, peerId: PeerId? = nil, a } } return CacheUsageStats(media: finalMedia, mediaResourceIds: finalMediaResourceIds, peers: peers, otherSize: otherSize, otherPaths: otherPaths, cacheSize: cacheSize, tempPaths: tempPaths, tempSize: tempSize, immutableSize: immutableSize) - } |> mapError { _ -> CollectCacheUsageStatsError in preconditionFailure() } + } |> mapError { _ -> CollectCacheUsageStatsError in } |> mapToSignal { stats -> Signal in return .fail(.done(stats)) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/AccessSecureId.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/AccessSecureId.swift index 96e678f46e..c59f6e35da 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/AccessSecureId.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/AccessSecureId.swift @@ -17,7 +17,9 @@ func encryptSecureData(key: Data, iv: Data, data: Data, decrypt: Bool) -> Data? } func verifySecureSecret(_ data: Data) -> Bool { - guard data.withUnsafeBytes({ (bytes: UnsafePointer) -> Bool in + guard data.withUnsafeBytes({ rawBytes -> Bool in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + var checksum: UInt32 = 0 for i in 0 ..< data.count { checksum += UInt32(bytes.advanced(by: i).pointee) @@ -52,7 +54,9 @@ func decryptedSecureSecret(encryptedSecretData: Data, password: String, derivati let secretHashData = sha256Digest(decryptedSecret) var secretId: Int64 = 0 - secretHashData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + secretHashData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(&secretId, bytes, 8) } @@ -66,7 +70,9 @@ func decryptedSecureSecret(encryptedSecretData: Data, password: String, derivati func encryptedSecureSecret(secretData: Data, password: String, inputDerivation: TwoStepSecurePasswordDerivation) -> (data: Data, salt: TwoStepSecurePasswordDerivation, id: Int64)? { let secretHashData = sha256Digest(secretData) var secretId: Int64 = 0 - secretHashData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + secretHashData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(&secretId, bytes, 8) } @@ -92,14 +98,18 @@ func generateSecureSecretData() -> Data? { var secretData = Data(count: 32) let secretDataCount = secretData.count - guard secretData.withUnsafeMutableBytes({ (bytes: UnsafeMutablePointer) -> Bool in + guard secretData.withUnsafeMutableBytes({ rawBytes -> Bool in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + let copyResult = SecRandomCopyBytes(nil, 32, bytes) return copyResult == errSecSuccess }) else { return nil } - secretData.withUnsafeMutableBytes({ (bytes: UnsafeMutablePointer) in + secretData.withUnsafeMutableBytes({ rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + while true { var checksum: UInt32 = 0 for i in 0 ..< secretDataCount { @@ -173,7 +183,9 @@ func _internal_accessSecureId(network: Network, password: String) -> Signal<(con |> map { decryptedSecret in let secretHashData = sha256Digest(decryptedSecret) var secretId: Int64 = 0 - secretHashData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + secretHashData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(&secretId, bytes, 8) } return (SecureIdAccessContext(secret: decryptedSecret, id: secretId), settings) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift index 9bea496571..a979781b54 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/RequestSecureIdForm.swift @@ -289,7 +289,7 @@ public func requestSecureIdForm(postbox: Postbox, network: Network, peerId: Peer } }, termsUrl: termsUrl, encryptedValues: values, errors: errors) } - } |> mapError { _ in return RequestSecureIdFormError.generic } + } |> mapError { _ -> RequestSecureIdFormError in } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift index f581816a7f..dc8d6bcb9a 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SaveSecureIdValue.swift @@ -55,7 +55,9 @@ func decryptedSecureValueAccessContext(context: SecureIdAccessContext, encrypted let valueSecretHash = sha512Digest(valueSecret) var valueSecretIdValue: Int64 = 0 - valueSecretHash.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + valueSecretHash.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(&valueSecretIdValue, bytes.advanced(by: valueSecretHash.count - 8), 8) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdPadding.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdPadding.swift index 9d738ff468..e6188bfe09 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdPadding.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdPadding.swift @@ -4,10 +4,14 @@ func paddedSecureIdData(_ data: Data) -> Data { var paddingCount = Int(47 + arc4random_uniform(255 - 47)) paddingCount -= ((data.count + paddingCount) % 16) var result = Data(count: paddingCount + data.count) - result.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + result.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + bytes.advanced(by: 0).pointee = UInt8(paddingCount) arc4random_buf(bytes.advanced(by: 1), paddingCount - 1) - data.withUnsafeBytes { (source: UnsafePointer) -> Void in + data.withUnsafeBytes { rawSource -> Void in + let source = rawSource.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes.advanced(by: paddingCount), source, data.count) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueAccessContext.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueAccessContext.swift index 9bfc8befa6..88bc31d1ff 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueAccessContext.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdValueAccessContext.swift @@ -25,7 +25,9 @@ public func generateSecureIdValueAccessContext() -> SecureIdValueAccessContext? } let secretHashData = sha512Digest(secret) var secretHash: Int64 = 0 - secretHashData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + secretHashData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(&secretHash, bytes.advanced(by: secretHashData.count - 8), 8) } return SecureIdValueAccessContext(secret: secret, id: secretHash) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift index de72484f17..59bc00b993 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/UploadSecureIdFile.swift @@ -90,7 +90,6 @@ func decryptedSecureIdFile(context: SecureIdAccessContext, encryptedData: Data, public func uploadSecureIdFile(context: SecureIdAccessContext, postbox: Postbox, network: Network, resource: MediaResource) -> Signal { return postbox.mediaBox.resourceData(resource) |> mapError { _ -> UploadSecureIdFileError in - return .generic } |> mapToSignal { next -> Signal in if !next.complete { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift index 8b50cb3cd7..11c4e64391 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/ImportStickers.swift @@ -38,7 +38,7 @@ func _internal_uploadSticker(account: Account, peer: Peer, resource: MediaResour return .fail(.generic) } return uploadedSticker(postbox: account.postbox, network: account.network, resource: resource) - |> mapError { _ -> UploadStickerError in return .generic } + |> mapError { _ -> UploadStickerError in } |> mapToSignal { result -> Signal in switch result.content { case .error: diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift index 34a3670355..b94dbe42dc 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift @@ -175,7 +175,7 @@ func _internal_searchStickers(account: Account, query: String, scope: SearchStic var cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query))) as? CachedStickerQueryResult let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) - let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration) as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue let searchStickersConfiguration = SearchStickersConfiguration.with(appConfiguration: appConfiguration) if let currentCached = cached, currentTime > currentCached.timestamp + searchStickersConfiguration.cacheTimeout { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift index d7c71c93d4..2ef5a55c64 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/StickerSetInstallation.swift @@ -61,8 +61,8 @@ func _internal_requestStickerSet(postbox: Postbox, network: Network, reference: info = StickerPackCollectionInfo(apiSet: set, namespace: Namespaces.ItemCollection.CloudStickerPacks) switch set { - case let .stickerSet(data): - installed = (data.flags & (1 << 0) != 0) + case let .stickerSet(flags, _, _, _, _, _, _, _, _, _, _): + installed = (flags & (1 << 0) != 0) } var indexKeysByFile: [MediaId: [MemoryBuffer]] = [:] @@ -98,7 +98,7 @@ func _internal_requestStickerSet(postbox: Postbox, network: Network, reference: } if let collectionId = collectionId { - return localSignal(collectionId) |> mapError {_ in return .generic} |> mapToSignal { result -> Signal in + return localSignal(collectionId) |> mapError { _ -> RequestStickerSetError in } |> mapToSignal { result -> Signal in if let result = result { return .single(.local(info: result.0, items: result.1)) } else { @@ -192,7 +192,7 @@ func _internal_installStickerSetInteractively(account: Account, info: StickerPac collections.insert((info.id, info, items), at: 0) transaction.replaceItemCollections(namespace: info.id.namespace, itemCollections: collections) - } |> map { _ in return addResult} |> mapError {_ in return .generic} + } |> map { _ in return addResult} |> mapError { _ -> InstallStickerSetError in } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift b/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift index 518dba5b1d..713f294bb2 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Themes/ChatThemes.swift @@ -22,16 +22,20 @@ public struct ChatTheme: Codable, Equatable { let container = try decoder.container(keyedBy: StringCodingKey.self) self.emoji = try container.decode(String.self, forKey: "e") - self.theme = try container.decode(TelegramTheme.self, forKey: "t") - self.darkTheme = try container.decode(TelegramTheme.self, forKey: "dt") + + let themeData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "t") + self.theme = TelegramTheme(decoder: PostboxDecoder(buffer: MemoryBuffer(data: themeData.data))) + + let darkThemeData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "dt") + self.darkTheme = TelegramTheme(decoder: PostboxDecoder(buffer: MemoryBuffer(data: darkThemeData.data))) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(self.emoji, forKey: "e") - try container.encode(self.theme, forKey: "t") - try container.encode(self.darkTheme, forKey: "dt") + try container.encode(PostboxEncoder().encodeObjectToRawData(self.theme), forKey: "t") + try container.encode(PostboxEncoder().encodeObjectToRawData(self.darkTheme), forKey: "dt") } } diff --git a/submodules/TelegramCore/Sources/UpdatePeers.swift b/submodules/TelegramCore/Sources/UpdatePeers.swift index b221cfe80d..c97e0d8a12 100644 --- a/submodules/TelegramCore/Sources/UpdatePeers.swift +++ b/submodules/TelegramCore/Sources/UpdatePeers.swift @@ -152,9 +152,9 @@ func updateContacts(transaction: Transaction, apiUsers: [Api.User]) { for user in apiUsers { var isContact: Bool? switch user { - case let .user(user): - if (user.flags & (1 << 20)) == 0 { - isContact = (user.flags & (1 << 11)) != 0 + case let .user(flags, _, _, _, _, _, _, _, _, _, _, _, _): + if (flags & (1 << 20)) == 0 { + isContact = (flags & (1 << 11)) != 0 } case .userEmpty: isContact = false diff --git a/submodules/TelegramCore/Sources/Utils/Log.swift b/submodules/TelegramCore/Sources/Utils/Log.swift index 11ad4da33c..c12f70b4f0 100644 --- a/submodules/TelegramCore/Sources/Utils/Log.swift +++ b/submodules/TelegramCore/Sources/Utils/Log.swift @@ -198,7 +198,9 @@ public final class Logger { var fileEvents: [(Double, String)] = [] if let data = try? Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedRead) { let dataLength = data.count - data.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + data.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + var offset = 0 while offset < dataLength { let remainingLength = dataLength - offset @@ -341,7 +343,9 @@ public final class Logger { if let currentFile = currentFile { if let data = content.data(using: .utf8) { - data.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + data.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + let _ = currentFile.write(bytes, count: data.count) } var newline: UInt8 = 0x0a @@ -448,7 +452,9 @@ public final class Logger { if let currentFile = currentFile { let contentDataCount = contentData.count - contentData.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + contentData.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + let _ = currentFile.write(bytes, count: contentDataCount) } if let shortFile = self.shortFile { diff --git a/submodules/TelegramCore/Sources/Utils/PeerUtils.swift b/submodules/TelegramCore/Sources/Utils/PeerUtils.swift index 70f32297a1..5efc7e35d6 100644 --- a/submodules/TelegramCore/Sources/Utils/PeerUtils.swift +++ b/submodules/TelegramCore/Sources/Utils/PeerUtils.swift @@ -57,23 +57,34 @@ public extension Peer { switch self { case let user as TelegramUser: if let firstName = user.firstName, let lastName = user.lastName, !firstName.isEmpty && !lastName.isEmpty { - return [firstName.substring(to: firstName.index(after: firstName.startIndex)).uppercased(), lastName.substring(to: lastName.index(after: lastName.startIndex)).uppercased()] + return [ + String(firstName[.. Signal { return uploadedWallpaper(postbox: account.postbox, network: account.network, resource: resource) - |> mapError { _ -> UploadWallpaperError in return .generic } + |> mapError { _ -> UploadWallpaperError in } |> mapToSignal { result -> Signal<(UploadWallpaperStatus, MediaResource?), UploadWallpaperError> in switch result.content { case .error: diff --git a/submodules/TelegramIntents/Sources/TelegramIntents.swift b/submodules/TelegramIntents/Sources/TelegramIntents.swift index dcf9261f8a..64378d8a68 100644 --- a/submodules/TelegramIntents/Sources/TelegramIntents.swift +++ b/submodules/TelegramIntents/Sources/TelegramIntents.swift @@ -69,7 +69,7 @@ public func donateSendMessageIntent(account: Account, sharedContext: SharedAccou return sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.intentsSettings]) |> take(1) |> mapToSignal { sharedData -> Signal<[(Peer, SendMessageIntentSubject)], NoError> in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings] as? IntentsSettings) ?? IntentsSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings]?.get(IntentsSettings.self) ?? IntentsSettings.defaultSettings if let accountId = settings.account, accountId != account.peerId { return .single([]) } diff --git a/submodules/TelegramPermissionsUI/Sources/PermissionSplitTest.swift b/submodules/TelegramPermissionsUI/Sources/PermissionSplitTest.swift index 19cb69e699..a64a7227b3 100644 --- a/submodules/TelegramPermissionsUI/Sources/PermissionSplitTest.swift +++ b/submodules/TelegramPermissionsUI/Sources/PermissionSplitTest.swift @@ -99,7 +99,7 @@ public struct PermissionUISplitTest: SplitTest { public func permissionUISplitTest(postbox: Postbox) -> Signal { return postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> mapToSignal { view -> Signal in - if let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration, appConfiguration.data != nil { + if let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self), appConfiguration.data != nil { let (config, bucket) = PermissionUISplitTest.Configuration.with(appConfiguration: appConfiguration) return .single(PermissionUISplitTest(postbox: postbox, bucket: bucket, configuration: config)) } else { diff --git a/submodules/TelegramPresentationData/Sources/PresentationData.swift b/submodules/TelegramPresentationData/Sources/PresentationData.swift index a54199e3d7..f4049c15d5 100644 --- a/submodules/TelegramPresentationData/Sources/PresentationData.swift +++ b/submodules/TelegramPresentationData/Sources/PresentationData.swift @@ -232,57 +232,57 @@ public final class InitialPresentationDataAndSettings { public func currentPresentationDataAndSettings(accountManager: AccountManager, systemUserInterfaceStyle: WindowUserInterfaceStyle) -> Signal { return accountManager.transaction { transaction -> InitialPresentationDataAndSettings in let localizationSettings: LocalizationSettings? - if let current = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings { + if let current = transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self) { localizationSettings = current } else { localizationSettings = nil } let themeSettings: PresentationThemeSettings - if let current = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings) as? PresentationThemeSettings { + if let current = transaction.getSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings)?.get(PresentationThemeSettings.self) { themeSettings = current } else { themeSettings = PresentationThemeSettings.defaultSettings } let automaticMediaDownloadSettings: MediaAutoDownloadSettings - if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings) as? MediaAutoDownloadSettings { + if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings)?.get(MediaAutoDownloadSettings.self) { automaticMediaDownloadSettings = value } else { automaticMediaDownloadSettings = MediaAutoDownloadSettings.defaultSettings } let autodownloadSettings: AutodownloadSettings - if let value = transaction.getSharedData(SharedDataKeys.autodownloadSettings) as? AutodownloadSettings { + if let value = transaction.getSharedData(SharedDataKeys.autodownloadSettings)?.get(AutodownloadSettings.self) { autodownloadSettings = value } else { autodownloadSettings = .defaultSettings } let callListSettings: CallListSettings - if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings) as? CallListSettings { + if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings)?.get(CallListSettings.self) { callListSettings = value } else { callListSettings = CallListSettings.defaultSettings } let inAppNotificationSettings: InAppNotificationSettings - if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings) as? InAppNotificationSettings { + if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings)?.get(InAppNotificationSettings.self) { inAppNotificationSettings = value } else { inAppNotificationSettings = InAppNotificationSettings.defaultSettings } let mediaInputSettings: MediaInputSettings - if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.mediaInputSettings) as? MediaInputSettings { + if let value = transaction.getSharedData(ApplicationSpecificSharedDataKeys.mediaInputSettings)?.get(MediaInputSettings.self) { mediaInputSettings = value } else { mediaInputSettings = MediaInputSettings.defaultSettings } - let experimentalUISettings: ExperimentalUISettings = (transaction.getSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings) as? ExperimentalUISettings) ?? ExperimentalUISettings.defaultSettings + let experimentalUISettings: ExperimentalUISettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings)?.get(ExperimentalUISettings.self) ?? ExperimentalUISettings.defaultSettings - let contactSettings: ContactSynchronizationSettings = (transaction.getSharedData(ApplicationSpecificSharedDataKeys.contactSynchronizationSettings) as? ContactSynchronizationSettings) ?? ContactSynchronizationSettings.defaultSettings + let contactSettings: ContactSynchronizationSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.contactSynchronizationSettings)?.get(ContactSynchronizationSettings.self) ?? ContactSynchronizationSettings.defaultSettings let effectiveTheme: PresentationThemeReference let parameters = AutomaticThemeSwitchParameters(settings: themeSettings.automaticThemeSwitchSetting) @@ -569,13 +569,13 @@ public func updatedPresentationData(accountManager: AccountManager mapToSignal { sharedData, systemUserInterfaceStyle -> Signal in let themeSettings: PresentationThemeSettings - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) { themeSettings = current } else { themeSettings = PresentationThemeSettings.defaultSettings } - let contactSettings: ContactSynchronizationSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings ?? ContactSynchronizationSettings.defaultSettings + let contactSettings: ContactSynchronizationSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]?.get(ContactSynchronizationSettings.self) ?? ContactSynchronizationSettings.defaultSettings var currentColors = themeSettings.themeSpecificAccentColors[themeSettings.theme.index] if let colors = currentColors, colors.baseColor == .theme { @@ -639,7 +639,7 @@ public func updatedPresentationData(accountManager: AccountManager map { preferences -> LimitsConfiguration in - return preferences.values[PreferencesKeys.limitsConfiguration] as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + return preferences.values[PreferencesKeys.limitsConfiguration]?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue } self.currentLimitsConfiguration = Atomic(value: limitsConfiguration) @@ -462,14 +462,14 @@ private final class ChatLocationContextHolderImpl: ChatLocationContextHolder { } func getAppConfiguration(transaction: Transaction) -> AppConfiguration { - let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration) as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue return appConfiguration } func getAppConfiguration(postbox: Postbox) -> Signal { return postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { view -> AppConfiguration in - let appConfiguration: AppConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue return appConfiguration } |> distinctUntilChanged diff --git a/submodules/TelegramUI/Sources/AppDelegate.swift b/submodules/TelegramUI/Sources/AppDelegate.swift index 5483fabe3b..e4e14c547f 100644 --- a/submodules/TelegramUI/Sources/AppDelegate.swift +++ b/submodules/TelegramUI/Sources/AppDelegate.swift @@ -34,6 +34,7 @@ import LightweightAccountData import TelegramAudio import DebugSettingsUI import BackgroundTasks +import UIKitRuntimeUtils #if canImport(AppCenter) import AppCenter @@ -99,14 +100,14 @@ private class ApplicationStatusBarHost: StatusBarHost { func setStatusBarStyle(_ style: UIStatusBarStyle, animated: Bool) { if self.shouldChangeStatusBarStyle?(style) ?? true { - self.application.setStatusBarStyle(style, animated: animated) + self.application.internalSetStatusBarStyle(style, animated: animated) } } var shouldChangeStatusBarStyle: ((UIStatusBarStyle) -> Bool)? func setStatusBarHidden(_ value: Bool, animated: Bool) { - self.application.setStatusBarHidden(value, with: animated ? .fade : .none) + self.application.internalSetStatusBarHidden(value, animation: animated ? .fade : .none) } var keyboardWindow: UIWindow? { @@ -175,7 +176,7 @@ final class SharedApplicationContext { } } -@objc(AppDelegate) class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate, UNUserNotificationCenterDelegate, UIAlertViewDelegate { +@objc(AppDelegate) class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate, UNUserNotificationCenterDelegate { @objc var window: UIWindow? var nativeWindow: (UIWindow & WindowHost)? var mainWindow: Window1! @@ -236,14 +237,6 @@ final class SharedApplicationContext { private var alertActions: (primary: (() -> Void)?, other: (() -> Void)?)? - func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { - if buttonIndex == alertView.firstOtherButtonIndex { - self.alertActions?.other?() - } else { - self.alertActions?.primary?() - } - } - private let deviceToken = Promise(nil) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { @@ -421,7 +414,7 @@ final class SharedApplicationContext { }, autolockDeadine: autolockDeadine, encryptionProvider: OpenSSLEncryptionProvider()) guard let appGroupUrl = maybeAppGroupUrl else { - UIAlertView(title: nil, message: "Error 2", delegate: nil, cancelButtonTitle: "OK").show() + self.mainWindow?.presentNative(UIAlertController(title: nil, message: "Error 2", preferredStyle: .alert)) return true } @@ -929,7 +922,7 @@ final class SharedApplicationContext { sharedApplicationContext.sharedContext.mediaManager.overlayMediaManager.attachOverlayMediaController(sharedApplicationContext.overlayMediaController) return accountManager.transaction { transaction -> (SharedApplicationContext, LoggingSettings) in - return (sharedApplicationContext, transaction.getSharedData(SharedDataKeys.loggingSettings) as? LoggingSettings ?? LoggingSettings.defaultSettings) + return (sharedApplicationContext, transaction.getSharedData(SharedDataKeys.loggingSettings)?.get(LoggingSettings.self) ?? LoggingSettings.defaultSettings) } } self.sharedContextPromise.set(sharedContextSignal @@ -958,7 +951,7 @@ final class SharedApplicationContext { }) |> mapToSignal { context -> Signal<(AccountContext, CallListSettings)?, NoError> in return sharedApplicationContext.sharedContext.accountManager.transaction { transaction -> CallListSettings? in - return transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings) as? CallListSettings + return transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings)?.get(CallListSettings.self) } |> reduceLeft(value: nil) { current, updated -> CallListSettings? in var result: CallListSettings? @@ -1040,12 +1033,12 @@ final class SharedApplicationContext { } |> mapToSignal { accountAndOtherAccountPhoneNumbers -> Signal<(UnauthorizedAccount, LimitsConfiguration, CallListSettings, ((String, AccountRecordId, Bool)?, [(String, AccountRecordId, Bool)]))?, NoError> in return sharedApplicationContext.sharedContext.accountManager.transaction { transaction -> CallListSettings in - return transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings) as? CallListSettings ?? CallListSettings.defaultSettings + return transaction.getSharedData(ApplicationSpecificSharedDataKeys.callListSettings)?.get(CallListSettings.self) ?? CallListSettings.defaultSettings } |> mapToSignal { callListSettings -> Signal<(UnauthorizedAccount, LimitsConfiguration, CallListSettings, ((String, AccountRecordId, Bool)?, [(String, AccountRecordId, Bool)]))?, NoError> in if let (account, otherAccountPhoneNumbers) = accountAndOtherAccountPhoneNumbers { return account.postbox.transaction { transaction -> (UnauthorizedAccount, LimitsConfiguration, CallListSettings, ((String, AccountRecordId, Bool)?, [(String, AccountRecordId, Bool)]))? in - let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue return (account, limitsConfiguration, callListSettings, otherAccountPhoneNumbers) } } else { @@ -1313,7 +1306,7 @@ final class SharedApplicationContext { } if UIApplication.shared.isStatusBarHidden { - UIApplication.shared.setStatusBarHidden(false, with: .none) + UIApplication.shared.internalSetStatusBarHidden(false, animation: .none) } /*if #available(iOS 13.0, *) { @@ -2032,7 +2025,7 @@ final class SharedApplicationContext { private func registerForNotifications(context: AccountContextImpl, authorize: Bool = true, completion: @escaping (Bool) -> Void = { _ in }) { let presentationData = context.sharedContext.currentPresentationData.with { $0 } let _ = (context.sharedContext.accountManager.transaction { transaction -> Bool in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings) as? InAppNotificationSettings ?? InAppNotificationSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings)?.get(InAppNotificationSettings.self) ?? InAppNotificationSettings.defaultSettings return settings.displayNameOnLockscreen } |> deliverOnMainQueue).start(next: { displayNames in @@ -2257,7 +2250,7 @@ final class SharedApplicationContext { private func resetIntentsIfNeeded(context: AccountContextImpl) { let _ = (context.sharedContext.accountManager.transaction { transaction in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.intentsSettings) as? IntentsSettings ?? IntentsSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.intentsSettings)?.get(IntentsSettings.self) ?? IntentsSettings.defaultSettings if !settings.initiallyReset || settings.account == nil { if #available(iOS 10.0, *) { Queue.mainQueue().async { @@ -2265,7 +2258,7 @@ final class SharedApplicationContext { } } transaction.updateSharedData(ApplicationSpecificSharedDataKeys.intentsSettings, { _ in - return IntentsSettings(initiallyReset: true, account: context.account.peerId, contacts: settings.contacts, privateChats: settings.privateChats, savedMessages: settings.savedMessages, groups: settings.groups, onlyShared: settings.onlyShared) + return PreferencesEntry(IntentsSettings(initiallyReset: true, account: context.account.peerId, contacts: settings.contacts, privateChats: settings.privateChats, savedMessages: settings.savedMessages, groups: settings.groups, onlyShared: settings.onlyShared)) }) } }).start() diff --git a/submodules/TelegramUI/Sources/ApplicationContext.swift b/submodules/TelegramUI/Sources/ApplicationContext.swift index 8b53fab81c..5fe82ef45e 100644 --- a/submodules/TelegramUI/Sources/ApplicationContext.swift +++ b/submodules/TelegramUI/Sources/ApplicationContext.swift @@ -264,7 +264,7 @@ final class AuthorizedApplicationContext { self.inAppNotificationSettingsDisposable.set(((context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.inAppNotificationSettings])) |> deliverOnMainQueue).start(next: { [weak self] sharedData in if let strongSelf = self { - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) { let previousSettings = strongSelf.inAppNotificationSettings strongSelf.inAppNotificationSettings = settings if let previousSettings = previousSettings, previousSettings.displayNameOnLockscreen != settings.displayNameOnLockscreen { @@ -696,7 +696,7 @@ final class AuthorizedApplicationContext { let importableContacts = self.context.sharedContext.contactDataManager?.importable() ?? .single([:]) self.context.account.importableContacts.set(self.context.account.postbox.preferencesView(keys: [PreferencesKeys.contactsSettings]) |> mapToSignal { preferences -> Signal<[DeviceContactNormalizedPhoneNumber: ImportableDeviceContactData], NoError> in - let settings: ContactsSettings = (preferences.values[PreferencesKeys.contactsSettings] as? ContactsSettings) ?? .defaultSettings + let settings: ContactsSettings = preferences.values[PreferencesKeys.contactsSettings]?.get(ContactsSettings.self) ?? .defaultSettings if settings.synchronizeContacts { return importableContacts } else { @@ -720,7 +720,7 @@ final class AuthorizedApplicationContext { let showCallsTabSignal = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.callListSettings]) |> map { sharedData -> Bool in var value = CallListSettings.defaultSettings.showTab - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings] as? CallListSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.callListSettings]?.get(CallListSettings.self) { value = settings.showTab } return value diff --git a/submodules/TelegramUI/Sources/AudioWaveform.swift b/submodules/TelegramUI/Sources/AudioWaveform.swift index 01515cbead..954f810ae4 100644 --- a/submodules/TelegramUI/Sources/AudioWaveform.swift +++ b/submodules/TelegramUI/Sources/AudioWaveform.swift @@ -39,11 +39,11 @@ final class AudioWaveform: Equatable { var result = Data() result.count = numSamples * 2 - bitstream.withUnsafeBytes { (bytes: UnsafePointer) -> Void in - result.withUnsafeMutableBytes { (samples: UnsafeMutablePointer) -> Void in + bitstream.withUnsafeBytes { bytes -> Void in + result.withUnsafeMutableBytes { samples -> Void in let norm = Int64((1 << bitsPerSample) - 1) for i in 0 ..< numSamples { - samples[i] = Int16(Int64(getBits(data: bytes, length: bitstream.count, bitOffset: i * 5, numBits: 5)) * norm / norm) + samples.baseAddress!.assumingMemoryBound(to: Int16.self)[i] = Int16(Int64(getBits(data: bytes.baseAddress!.assumingMemoryBound(to: Int8.self), length: bitstream.count, bitOffset: i * 5, numBits: 5)) * norm / norm) } } } @@ -59,8 +59,12 @@ final class AudioWaveform: Equatable { let maxSample: Int32 = self.peak - self.samples.withUnsafeBytes { (samples: UnsafePointer) -> Void in - result.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + self.samples.withUnsafeBytes { rawSamples -> Void in + let samples = rawSamples.baseAddress!.assumingMemoryBound(to: Int16.self) + + result.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int16.self) + for i in 0 ..< numSamples { let value: Int32 = min(Int32(31), abs(Int32(samples[i])) * 31 / maxSample) if i == 99 { diff --git a/submodules/TelegramUI/Sources/AudioWaveformNode.swift b/submodules/TelegramUI/Sources/AudioWaveformNode.swift index 691bab2228..174c957ad0 100644 --- a/submodules/TelegramUI/Sources/AudioWaveformNode.swift +++ b/submodules/TelegramUI/Sources/AudioWaveformNode.swift @@ -90,7 +90,9 @@ final class AudioWaveformNode: ASDisplayNode { } if let waveform = parameters.waveform { - waveform.samples.withUnsafeBytes { (samples: UnsafePointer) -> Void in + waveform.samples.withUnsafeBytes { rawSamples -> Void in + let samples = rawSamples.baseAddress!.assumingMemoryBound(to: UInt16.self) + let peakHeight: CGFloat = 12.0 let maxReadSamples = waveform.samples.count / 2 diff --git a/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift b/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift index cd59666642..70640ea1a9 100644 --- a/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift +++ b/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift @@ -154,7 +154,7 @@ final class AuthorizationSequenceSplashController: ViewController { private func activateLocalization(_ code: String) { let currentCode = self.accountManager.transaction { transaction -> String in - if let current = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings { + if let current = transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self) { return current.primaryComponent.languageCode } else { return "en" @@ -187,7 +187,7 @@ final class AuthorizationSequenceSplashController: ViewController { strongSelf.activateLocalizationDisposable.set(TelegramEngineUnauthorized(account: strongSelf.account).localization.downloadAndApplyLocalization(accountManager: accountManager, languageCode: code).start(completed: { let _ = (accountManager.transaction { transaction -> PresentationStrings? in let localizationSettings: LocalizationSettings? - if let current = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings { + if let current = transaction.getSharedData(SharedDataKeys.localizationSettings)?.get(LocalizationSettings.self) { localizationSettings = current } else { localizationSettings = nil diff --git a/submodules/TelegramUI/Sources/ChatController.swift b/submodules/TelegramUI/Sources/ChatController.swift index bba2c26553..262b6816e5 100644 --- a/submodules/TelegramUI/Sources/ChatController.swift +++ b/submodules/TelegramUI/Sources/ChatController.swift @@ -3889,7 +3889,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G let themeSettings = context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.presentationThemeSettings]) |> map { sharedData -> PresentationThemeSettings in let themeSettings: PresentationThemeSettings - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) { themeSettings = current } else { themeSettings = PresentationThemeSettings.defaultSettings @@ -4012,7 +4012,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.stickerSettingsDisposable = combineLatest(queue: Queue.mainQueue(), context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.stickerSettings]), self.disableStickerAnimationsPromise.get()).start(next: { [weak self] sharedData, disableStickerAnimations in var stickerSettings = StickerSettings.defaultSettings - if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings] as? StickerSettings { + if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.stickerSettings]?.get(StickerSettings.self) { stickerSettings = value } @@ -9169,7 +9169,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G private func presentAttachmentMenu(editMediaOptions: MessageMediaEditingOptions?, editMediaReference: AnyMediaReference?) { let _ = (self.context.sharedContext.accountManager.transaction { transaction -> GeneratedMediaStoreSettings in - let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings + let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings)?.get(GeneratedMediaStoreSettings.self) return entry ?? GeneratedMediaStoreSettings.defaultSettings } |> deliverOnMainQueue).start(next: { [weak self] settings in @@ -9546,7 +9546,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G private func presentMediaPicker(fileMode: Bool, editingMedia: Bool, completion: @escaping ([Any], Bool, Int32) -> Void) { let postbox = self.context.account.postbox let _ = (self.context.sharedContext.accountManager.transaction { transaction -> Signal<(GeneratedMediaStoreSettings, SearchBotsConfiguration), NoError> in - let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings + let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings)?.get(GeneratedMediaStoreSettings.self) return postbox.transaction { transaction -> (GeneratedMediaStoreSettings, SearchBotsConfiguration) in let configuration = currentSearchBotsConfiguration(transaction: transaction) return (entry ?? GeneratedMediaStoreSettings.defaultSettings, configuration) @@ -9679,7 +9679,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G } let _ = (self.context.account.postbox.transaction { transaction -> SearchBotsConfiguration in - if let entry = transaction.getPreferencesEntry(key: PreferencesKeys.searchBotsConfiguration) as? SearchBotsConfiguration { + if let entry = transaction.getPreferencesEntry(key: PreferencesKeys.searchBotsConfiguration)?.get(SearchBotsConfiguration.self) { return entry } else { return SearchBotsConfiguration.defaultValue @@ -10381,7 +10381,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G private func displayPasteMenu(_ images: [UIImage]) { let _ = (self.context.sharedContext.accountManager.transaction { transaction -> GeneratedMediaStoreSettings in - let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings) as? GeneratedMediaStoreSettings + let entry = transaction.getSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings)?.get(GeneratedMediaStoreSettings.self) return entry ?? GeneratedMediaStoreSettings.defaultSettings } |> deliverOnMainQueue).start(next: { [weak self] settings in @@ -12419,7 +12419,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G var parsedUrlValue: URL? if let parsed = URL(string: string) { parsedUrlValue = parsed - } else if let encoded = (string as NSString).addingPercentEscapes(using: String.Encoding.utf8.rawValue), let parsed = URL(string: encoded) { + } else if let encoded = (string as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed), let parsed = URL(string: encoded) { parsedUrlValue = parsed } diff --git a/submodules/TelegramUI/Sources/ChatControllerNode.swift b/submodules/TelegramUI/Sources/ChatControllerNode.swift index 7c0af628ab..a7ef4bd03c 100644 --- a/submodules/TelegramUI/Sources/ChatControllerNode.swift +++ b/submodules/TelegramUI/Sources/ChatControllerNode.swift @@ -438,7 +438,7 @@ class ChatControllerNode: ASDisplayNode, UIScrollViewDelegate { self.interactiveEmojisDisposable = (self.context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { preferencesView -> InteractiveEmojiConfiguration in - let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue return InteractiveEmojiConfiguration.with(appConfiguration: appConfiguration) } |> deliverOnMainQueue).start(next: { [weak self] emojis in diff --git a/submodules/TelegramUI/Sources/ChatHistoryListNode.swift b/submodules/TelegramUI/Sources/ChatHistoryListNode.swift index 31209b19ff..cc3ab17307 100644 --- a/submodules/TelegramUI/Sources/ChatHistoryListNode.swift +++ b/submodules/TelegramUI/Sources/ChatHistoryListNode.swift @@ -1166,7 +1166,7 @@ public final class ChatHistoryListNode: ListView, ChatHistoryNode { let appConfiguration = context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> take(1) |> map { view in - return view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + return view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue } var didSetPresentationData = false diff --git a/submodules/TelegramUI/Sources/ChatHistoryViewForLocation.swift b/submodules/TelegramUI/Sources/ChatHistoryViewForLocation.swift index 5e35e755f6..91ee4348bd 100644 --- a/submodules/TelegramUI/Sources/ChatHistoryViewForLocation.swift +++ b/submodules/TelegramUI/Sources/ChatHistoryViewForLocation.swift @@ -22,12 +22,12 @@ func preloadedChatHistoryViewForLocation(_ location: ChatHistoryLocationInput, c |> castError(Bool.self) |> mapToSignal { update -> Signal in switch update { - case let .Loading(value): - if case .Generic(.FillHole) = value.type { + case let .Loading(_, type): + if case .Generic(.FillHole) = type { return .fail(true) } - case let .HistoryView(value): - if case .Generic(.FillHole) = value.type { + case let .HistoryView(_, type, _, _, _, _, _): + if case .Generic(.FillHole) = type { return .fail(true) } } diff --git a/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift b/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift index 7a48c4c9dd..2a09397f6f 100644 --- a/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift +++ b/submodules/TelegramUI/Sources/ChatInterfaceStateContextMenus.swift @@ -229,14 +229,14 @@ func messageMediaEditingOptions(message: Message) -> MessageMediaEditingOptions return [] case .Animated: return [] - case let .Video(video): - if video.flags.contains(.instantRoundVideo) { + case let .Video(_, _, flags): + if flags.contains(.instantRoundVideo) { return [] } else { options.formUnion([.imageOrVideo, .file]) } - case let .Audio(audio): - if audio.isVoice { + case let .Audio(isVoice, _, _, _, _): + if isVoice { return [] } else { if let _ = message.groupingKey { @@ -464,7 +464,7 @@ func contextMenuForChatPresentationInterfaceState(chatPresentationInterfaceState } let loadLimits = context.account.postbox.transaction { transaction -> LimitsConfiguration in - return transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + return transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue } let cachedData = context.account.postbox.transaction { transaction -> CachedPeerData? in @@ -1131,7 +1131,7 @@ private func canPerformDeleteActions(limits: LimitsConfiguration, accountPeerId: func chatAvailableMessageActionsImpl(postbox: Postbox, accountPeerId: PeerId, messageIds: Set, messages: [MessageId: Message] = [:], peers: [PeerId: Peer] = [:]) -> Signal { return postbox.transaction { transaction -> ChatAvailableMessageActions in - let limitsConfiguration: LimitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + let limitsConfiguration: LimitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue var optionsMap: [MessageId: ChatAvailableMessageActionOptions] = [:] var banPeer: Peer? var hadPersonalIncoming = false @@ -1166,8 +1166,8 @@ func chatAvailableMessageActionsImpl(postbox: Postbox, accountPeerId: PeerId, me if let message = getMessage(id) { for media in message.media { if let file = media as? TelegramMediaFile, file.isSticker { - for case let .Sticker(sticker) in file.attributes { - if let _ = sticker.packReference { + for case let .Sticker(_, packReference, _) in file.attributes { + if let _ = packReference { optionsMap[id]!.insert(.viewStickerPack) } break diff --git a/submodules/TelegramUI/Sources/ChatInterfaceStateContextQueries.swift b/submodules/TelegramUI/Sources/ChatInterfaceStateContextQueries.swift index ee8fa435d0..a57dba33ed 100644 --- a/submodules/TelegramUI/Sources/ChatInterfaceStateContextQueries.swift +++ b/submodules/TelegramUI/Sources/ChatInterfaceStateContextQueries.swift @@ -102,11 +102,11 @@ private func updatedContextQueryResultStateForQuery(context: AccountContext, pee let stickerConfiguration = context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { preferencesView -> StickersSearchConfiguration in - let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue return StickersSearchConfiguration.with(appConfiguration: appConfiguration) } let stickerSettings = context.sharedContext.accountManager.transaction { transaction -> StickerSettings in - let stickerSettings: StickerSettings = (transaction.getSharedData(ApplicationSpecificSharedDataKeys.stickerSettings) as? StickerSettings) ?? .defaultSettings + let stickerSettings: StickerSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.stickerSettings)?.get(StickerSettings.self) ?? .defaultSettings return stickerSettings } diff --git a/submodules/TelegramUI/Sources/ChatMediaInputNode.swift b/submodules/TelegramUI/Sources/ChatMediaInputNode.swift index 819b35c16f..05ccded636 100644 --- a/submodules/TelegramUI/Sources/ChatMediaInputNode.swift +++ b/submodules/TelegramUI/Sources/ChatMediaInputNode.swift @@ -1077,7 +1077,7 @@ final class ChatMediaInputNode: ChatInputNode { guard let view = views.views[preferencesViewKey] as? PreferencesView else { return defaultReactions } - guard let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration else { + guard let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { return defaultReactions } guard let data = appConfiguration.data, let emojis = data["gif_search_emojies"] as? [String] else { diff --git a/submodules/TelegramUI/Sources/ChatMessageAnimatedStickerItemNode.swift b/submodules/TelegramUI/Sources/ChatMessageAnimatedStickerItemNode.swift index 9050165f81..292d5a5b60 100644 --- a/submodules/TelegramUI/Sources/ChatMessageAnimatedStickerItemNode.swift +++ b/submodules/TelegramUI/Sources/ChatMessageAnimatedStickerItemNode.swift @@ -1388,7 +1388,7 @@ class ChatMessageAnimatedStickerItemNode: ChatMessageItemView { let appConfiguration = item.context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> take(1) |> map { view in - return view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + return view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue } if let text = self.item?.message.text, var firstScalar = text.unicodeScalars.first { diff --git a/submodules/TelegramUI/Sources/ChatMessageAvatarAccessoryItem.swift b/submodules/TelegramUI/Sources/ChatMessageAvatarAccessoryItem.swift index bf81f9ace3..eb86e97f8f 100644 --- a/submodules/TelegramUI/Sources/ChatMessageAvatarAccessoryItem.swift +++ b/submodules/TelegramUI/Sources/ChatMessageAvatarAccessoryItem.swift @@ -168,8 +168,8 @@ final class ChatMessageAvatarAccessoryItemNode: ListViewAccessoryItemNode { func setPeer(context: AccountContext, theme: PresentationTheme, synchronousLoad: Bool, peer: Peer, authorOfMessage: MessageReference?, emptyColor: UIColor, controllerInteraction: ChatControllerInteraction) { self.controllerInteraction = controllerInteraction self.peer = peer - if let messageReference = authorOfMessage, case let .message(m) = messageReference.content { - self.messageId = m.id + if let messageReference = authorOfMessage, case let .message(_, id, _, _, _) = messageReference.content { + self.messageId = id } self.contextActionIsEnabled = peer.smallProfileImage != nil diff --git a/submodules/TelegramUI/Sources/ChatMessageBackground.swift b/submodules/TelegramUI/Sources/ChatMessageBackground.swift index e8acf53139..c618c7d7b9 100644 --- a/submodules/TelegramUI/Sources/ChatMessageBackground.swift +++ b/submodules/TelegramUI/Sources/ChatMessageBackground.swift @@ -101,7 +101,6 @@ class ChatMessageBackground: ASDisplayNode { func setType(type: ChatMessageBackgroundType, highlighted: Bool, graphics: PrincipalThemeEssentialGraphics, maskMode: Bool, hasWallpaper: Bool, transition: ContainedViewLayoutTransition, backgroundNode: WallpaperBackgroundNode?) { let previousType = self.type - let previousHighlighted = self.currentHighlighted if let currentType = previousType, currentType == type, self.currentHighlighted == highlighted, self.graphics === graphics, backgroundNode === self.backgroundNode, self.maskMode == maskMode, self.hasWallpaper == hasWallpaper { return } diff --git a/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift b/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift index 84e05988ae..7355ccd1f0 100644 --- a/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift +++ b/submodules/TelegramUI/Sources/ChatMessageBubbleItemNode.swift @@ -1335,22 +1335,26 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode var addedContentNodes: [(Message, Bool, ChatMessageBubbleContentNode)]? let (contentNodeMessagesAndClasses, needSeparateContainers) = contentNodeMessagesAndClassesForItem(item) - for (contentNodeMessage, contentNodeClass, attributes, bubbleAttributes) in contentNodeMessagesAndClasses { + for contentNodeItemValue in contentNodeMessagesAndClasses { + let contentNodeItem = contentNodeItemValue as (message: Message, type: AnyClass, attributes: ChatMessageEntryAttributes, bubbleAttributes: BubbleItemAttributes) + var found = false - for (currentMessage, currentClass, supportsMosaic, currentLayout) in currentContentClassesPropertiesAndLayouts { - if currentClass == contentNodeClass && currentMessage.stableId == contentNodeMessage.stableId { - contentPropertiesAndPrepareLayouts.append((contentNodeMessage, supportsMosaic, attributes, bubbleAttributes, currentLayout)) + for currentNodeItemValue in currentContentClassesPropertiesAndLayouts { + let currentNodeItem = currentNodeItemValue as (message: Message, type: AnyClass, supportsMosaic: Bool, currentLayout: (ChatMessageBubbleContentItem, ChatMessageItemLayoutConstants, ChatMessageBubblePreparePosition, Bool?, CGSize) -> (ChatMessageBubbleContentProperties, CGSize?, CGFloat, (CGSize, ChatMessageBubbleContentPosition) -> (CGFloat, (CGFloat) -> (CGSize, (ListViewItemUpdateAnimation, Bool) -> Void)))) + + if currentNodeItem.type == contentNodeItem.type && currentNodeItem.message.stableId == contentNodeItem.message.stableId { + contentPropertiesAndPrepareLayouts.append((contentNodeItem.message, currentNodeItem.supportsMosaic, contentNodeItem.attributes, contentNodeItem.bubbleAttributes, currentNodeItem.currentLayout)) found = true break } } if !found { - let contentNode = (contentNodeClass as! ChatMessageBubbleContentNode.Type).init() - contentPropertiesAndPrepareLayouts.append((contentNodeMessage, contentNode.supportsMosaic, attributes, bubbleAttributes, contentNode.asyncLayoutContent())) + let contentNode = (contentNodeItem.type as! ChatMessageBubbleContentNode.Type).init() + contentPropertiesAndPrepareLayouts.append((contentNodeItem.message, contentNode.supportsMosaic, contentNodeItem.attributes, contentNodeItem.bubbleAttributes, contentNode.asyncLayoutContent())) if addedContentNodes == nil { addedContentNodes = [] } - addedContentNodes!.append((contentNodeMessage, bubbleAttributes.isAttachment, contentNode)) + addedContentNodes!.append((contentNodeItem.message, contentNodeItem.bubbleAttributes.isAttachment, contentNode)) } } @@ -1862,8 +1866,10 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode findRemoved: for i in 0 ..< currentContentClassesPropertiesAndLayouts.count { let currentMessage = currentContentClassesPropertiesAndLayouts[i].0 let currentClass: AnyClass = currentContentClassesPropertiesAndLayouts[i].1 - for (contentNodeMessage, contentNodeClass, _, _) in contentNodeMessagesAndClasses { - if currentClass == contentNodeClass && currentMessage.stableId == contentNodeMessage.stableId { + for contentItemValue in contentNodeMessagesAndClasses { + let contentItem = contentItemValue as (message: Message, type: AnyClass, ChatMessageEntryAttributes, BubbleItemAttributes) + + if currentClass == contentItem.type && currentMessage.stableId == contentItem.message.stableId { continue findRemoved } } @@ -1944,7 +1950,12 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode bottomLeft = .merged bottomRight = .merged } else { - switch lastNodeTopPosition { + var switchValue = lastNodeTopPosition + if !"".isEmpty { + switchValue = .BubbleNeighbour + } + + switch switchValue { case .Neighbour: bottomLeft = .merged bottomRight = .merged @@ -2685,17 +2696,19 @@ class ChatMessageBubbleItemNode: ChatMessageItemView, ChatMessagePreviewItemNode } var sortedContentNodes: [ChatMessageBubbleContentNode] = [] - outer: for (message, nodeClass, _, _) in contentNodeMessagesAndClasses { + outer: for contentItemValue in contentNodeMessagesAndClasses { + let contentItem = contentItemValue as (message: Message, type: AnyClass, ChatMessageEntryAttributes, BubbleItemAttributes) + if let addedContentNodes = addedContentNodes { for (contentNodeMessage, _, contentNode) in addedContentNodes { - if type(of: contentNode) == nodeClass && contentNodeMessage.stableId == message.stableId { + if type(of: contentNode) == contentItem.type && contentNodeMessage.stableId == contentItem.message.stableId { sortedContentNodes.append(contentNode) continue outer } } } for contentNode in updatedContentNodes { - if type(of: contentNode) == nodeClass && contentNode.item?.message.stableId == message.stableId { + if type(of: contentNode) == contentItem.type && contentNode.item?.message.stableId == contentItem.message.stableId { sortedContentNodes.append(contentNode) continue outer } diff --git a/submodules/TelegramUI/Sources/ChatMessageDateHeader.swift b/submodules/TelegramUI/Sources/ChatMessageDateHeader.swift index ec201e8fa3..f1a3477e78 100644 --- a/submodules/TelegramUI/Sources/ChatMessageDateHeader.swift +++ b/submodules/TelegramUI/Sources/ChatMessageDateHeader.swift @@ -415,8 +415,8 @@ final class ChatMessageAvatarHeaderNode: ListViewItemHeaderNode { return } var messageId: MessageId? - if let messageReference = messageReference, case let .message(m) = messageReference.content { - messageId = m.id + if let messageReference = messageReference, case let .message(_, id, _, _, _) = messageReference.content { + messageId = id } strongSelf.controllerInteraction.openPeerContextMenu(peer, messageId, strongSelf.containerNode, strongSelf.containerNode.bounds, gesture) } diff --git a/submodules/TelegramUI/Sources/ChatMessageInteractiveMediaNode.swift b/submodules/TelegramUI/Sources/ChatMessageInteractiveMediaNode.swift index 4ee254e260..5b7b0e5f30 100644 --- a/submodules/TelegramUI/Sources/ChatMessageInteractiveMediaNode.swift +++ b/submodules/TelegramUI/Sources/ChatMessageInteractiveMediaNode.swift @@ -1103,12 +1103,12 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTransitio return } - let automaticDownload: Bool + /*let automaticDownload: Bool if let autoDownload = self.automaticDownload, case .full = autoDownload { automaticDownload = true } else { automaticDownload = false - } + }*/ var secretBeginTimeAndTimeout: (Double?, Double)? let isSecretMedia = message.containsSecretMedia @@ -1391,10 +1391,7 @@ final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTransitio case .Remote: state = .download(messageTheme.mediaOverlayControlColors.foregroundColor) if let file = self.media as? TelegramMediaFile { - if false, file.isAnimated && (!automaticDownload || !automaticPlayback) { - let string = "\(gifTitle) " + dataSizeString(file.size ?? 0, formatting: formatting) - badgeContent = .mediaDownload(backgroundColor: messageTheme.mediaDateAndStatusFillColor, foregroundColor: messageTheme.mediaDateAndStatusTextColor, duration: string, size: nil, muted: false, active: false) - } else { + do { let durationString = file.isAnimated ? gifTitle : stringForDuration(playerDuration > 0 ? playerDuration : (file.duration ?? 0), position: playerPosition) if wideLayout { if isMediaStreamable(message: message, media: file) { diff --git a/submodules/TelegramUI/Sources/ChatMessageItem.swift b/submodules/TelegramUI/Sources/ChatMessageItem.swift index 02c67b230a..2fd6411bc5 100644 --- a/submodules/TelegramUI/Sources/ChatMessageItem.swift +++ b/submodules/TelegramUI/Sources/ChatMessageItem.swift @@ -47,8 +47,8 @@ public enum ChatMessageItemContent: Sequence { var firstMessageAttributes: ChatMessageEntryAttributes { switch self { - case let .message(message): - return message.attributes + case let .message(_, _, _, attributes): + return attributes case let .group(messages): return messages[0].3 } @@ -58,10 +58,10 @@ public enum ChatMessageItemContent: Sequence { var index = 0 return AnyIterator { () -> (Message, ChatMessageEntryAttributes)? in switch self { - case let .message(message): + case let .message(message, _, _, attributes): if index == 0 { index += 1 - return (message.message, message.attributes) + return (message, attributes) } else { index += 1 return nil diff --git a/submodules/TelegramUI/Sources/ChatMessageItemView.swift b/submodules/TelegramUI/Sources/ChatMessageItemView.swift index 614713e13d..1595531c00 100644 --- a/submodules/TelegramUI/Sources/ChatMessageItemView.swift +++ b/submodules/TelegramUI/Sources/ChatMessageItemView.swift @@ -255,14 +255,14 @@ final class ChatMessageAccessibilityData { label = item.presentationData.strings.VoiceOver_Chat_YourSticker } } - case let .Audio(audio): + case let .Audio(isVoice, duration, title, performer, _): isSpecialFile = true if isSelected == nil { hint = item.presentationData.strings.VoiceOver_Chat_PlayHint } traits.insert(.startsMediaSession) - if audio.isVoice { - let durationString = voiceMessageDurationFormatter.string(from: Double(audio.duration)) ?? "" + if isVoice { + let durationString = voiceMessageDurationFormatter.string(from: Double(duration)) ?? "" if isIncoming { if announceIncomingAuthors, let authorName = authorName { label = item.presentationData.strings.VoiceOver_Chat_VoiceMessageFrom(authorName).string @@ -274,7 +274,7 @@ final class ChatMessageAccessibilityData { } text = item.presentationData.strings.VoiceOver_Chat_Duration(durationString).string } else { - let durationString = musicDurationFormatter.string(from: Double(audio.duration)) ?? "" + let durationString = musicDurationFormatter.string(from: Double(duration)) ?? "" if isIncoming { if announceIncomingAuthors, let authorName = authorName { label = item.presentationData.strings.VoiceOver_Chat_MusicFrom(authorName).string @@ -284,20 +284,20 @@ final class ChatMessageAccessibilityData { } else { label = item.presentationData.strings.VoiceOver_Chat_YourMusic } - let performer = audio.performer ?? "Unknown" - let title = audio.title ?? "Unknown" + let performer = performer ?? "Unknown" + let title = title ?? "Unknown" text = item.presentationData.strings.VoiceOver_Chat_MusicTitle(title, performer).string text.append(item.presentationData.strings.VoiceOver_Chat_Duration(durationString).string) } - case let .Video(video): + case let .Video(duration, _, flags): isSpecialFile = true if isSelected == nil { hint = item.presentationData.strings.VoiceOver_Chat_PlayHint } traits.insert(.startsMediaSession) - let durationString = voiceMessageDurationFormatter.string(from: Double(video.duration)) ?? "" - if video.flags.contains(.instantRoundVideo) { + let durationString = voiceMessageDurationFormatter.string(from: Double(duration)) ?? "" + if flags.contains(.instantRoundVideo) { if isIncoming { if announceIncomingAuthors, let authorName = authorName { label = item.presentationData.strings.VoiceOver_Chat_VideoMessageFrom(authorName).string @@ -895,10 +895,6 @@ public class ChatMessageItemView: ListViewItemNode { } override public var preferredAnimationCurve: (CGFloat) -> CGFloat { - if false, let item = self.item, let subject = item.associatedData.subject, case .forwardedMessages = subject { - return listViewAnimationCurveEaseInOut - } else { - return listViewAnimationCurveSystem - } + return listViewAnimationCurveSystem } } diff --git a/submodules/TelegramUI/Sources/ChatMessageWebpageBubbleContentNode.swift b/submodules/TelegramUI/Sources/ChatMessageWebpageBubbleContentNode.swift index d851547ee1..59f20e8060 100644 --- a/submodules/TelegramUI/Sources/ChatMessageWebpageBubbleContentNode.swift +++ b/submodules/TelegramUI/Sources/ChatMessageWebpageBubbleContentNode.swift @@ -290,7 +290,7 @@ final class ChatMessageWebpageBubbleContentNode: ChatMessageBubbleContentNode { case "telegram_message": actionTitle = item.presentationData.strings.Conversation_ViewMessage case "telegram_voicechat": - if let channel = item.message.peers[item.message.id.peerId] as? TelegramChannel, case let .broadcast = channel.info { + if let channel = item.message.peers[item.message.id.peerId] as? TelegramChannel, case .broadcast = channel.info { title = item.presentationData.strings.Conversation_LiveStream } else { title = item.presentationData.strings.Conversation_VoiceChat diff --git a/submodules/TelegramUI/Sources/ChatSearchResultsContollerNode.swift b/submodules/TelegramUI/Sources/ChatSearchResultsContollerNode.swift index 901788194a..1756c19d0d 100644 --- a/submodules/TelegramUI/Sources/ChatSearchResultsContollerNode.swift +++ b/submodules/TelegramUI/Sources/ChatSearchResultsContollerNode.swift @@ -203,9 +203,9 @@ class ChatSearchResultsControllerNode: ViewControllerTracingNode, UIScrollViewDe return } switch item.content { - case let .peer(peer): - if let message = peer.messages.first { - let chatController = strongSelf.context.sharedContext.makeChatController(context: strongSelf.context, chatLocation: .peer(peer.peer.peerId), subject: .message(id: message.id, highlight: true, timecode: nil), botStart: nil, mode: .standard(previewing: true)) + case let .peer(messages, peer, _, _, _, _, _, _, _, _, _, _): + if let message = messages.first { + let chatController = strongSelf.context.sharedContext.makeChatController(context: strongSelf.context, chatLocation: .peer(peer.peerId), subject: .message(id: message.id, highlight: true, timecode: nil), botStart: nil, mode: .standard(previewing: true)) chatController.canReadHistory.set(false) let contextController = ContextController(account: strongSelf.context.account, presentationData: strongSelf.presentationData, source: .controller(ContextControllerContentSourceImpl(controller: chatController, sourceNode: node)), items: .single([]), reactionItems: [], gesture: gesture) presentInGlobalOverlay(contextController) diff --git a/submodules/TelegramUI/Sources/ChatTextInputAudioRecordingOverlayButton.swift b/submodules/TelegramUI/Sources/ChatTextInputAudioRecordingOverlayButton.swift index a4940fff0f..c527609339 100644 --- a/submodules/TelegramUI/Sources/ChatTextInputAudioRecordingOverlayButton.swift +++ b/submodules/TelegramUI/Sources/ChatTextInputAudioRecordingOverlayButton.swift @@ -3,6 +3,7 @@ import UIKit import Display import AsyncDisplayKit import AppBundle +import ObjCRuntimeUtils private let innerCircleDiameter: CGFloat = 110.0 private let outerCircleDiameter = innerCircleDiameter + 50.0 @@ -138,7 +139,7 @@ final class ChatTextInputAudioRecordingOverlay { }) var currentScaleValue: CGFloat = outerCircleMinScale - if let currentScale = self.outerCircleNode.layer.value(forKeyPath: "transform.scale") as? AnyObject, currentScale.responds(to: Selector("floatValue")) { + if let currentScale = self.outerCircleNode.layer.floatValue(forKeyPath: "transform.scale") { currentScaleValue = CGFloat(currentScale.floatValue) } diff --git a/submodules/TelegramUI/Sources/ChatTextInputPanelNode.swift b/submodules/TelegramUI/Sources/ChatTextInputPanelNode.swift index 499549bcae..3443208630 100644 --- a/submodules/TelegramUI/Sources/ChatTextInputPanelNode.swift +++ b/submodules/TelegramUI/Sources/ChatTextInputPanelNode.swift @@ -14,6 +14,7 @@ import ImageTransparency import ActivityIndicator import AnimationUI import Speak +import ObjCRuntimeUtils private let accessoryButtonFont = Font.medium(14.0) private let counterFont = Font.with(size: 14.0, design: .regular, traits: [.monospacedNumbers]) @@ -1969,7 +1970,7 @@ class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDelegate { } func editableTextNodeTarget(forAction action: Selector) -> ASEditableTextNodeTargetForAction? { - if action == Selector(("_accessibilitySpeak:")) { + if action == makeSelectorFromString("_accessibilitySpeak:") { if case .format = self.inputMenu.state { return ASEditableTextNodeTargetForAction(target: nil) } else if let textInputNode = self.textInputNode, textInputNode.selectedRange.length > 0 { @@ -1977,7 +1978,7 @@ class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDelegate { } else { return ASEditableTextNodeTargetForAction(target: nil) } - } else if action == Selector(("_accessibilitySpeakSpellOut:")) { + } else if action == makeSelectorFromString("_accessibilitySpeakSpellOut:") { if case .format = self.inputMenu.state { return ASEditableTextNodeTargetForAction(target: nil) } else if let textInputNode = self.textInputNode, textInputNode.selectedRange.length > 0 { @@ -1986,9 +1987,9 @@ class ChatTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDelegate { return ASEditableTextNodeTargetForAction(target: nil) } } - else if action == Selector("_accessibilitySpeakLanguageSelection:") || action == Selector("_accessibilityPauseSpeaking:") || action == Selector("_accessibilitySpeakSentence:") { + else if action == makeSelectorFromString("_accessibilitySpeakLanguageSelection:") || action == makeSelectorFromString("_accessibilityPauseSpeaking:") || action == makeSelectorFromString("_accessibilitySpeakSentence:") { return ASEditableTextNodeTargetForAction(target: nil) - } else if action == Selector(("_showTextStyleOptions:")) { + } else if action == makeSelectorFromString("_showTextStyleOptions:") { if case .general = self.inputMenu.state { if let textInputNode = self.textInputNode, textInputNode.attributedText == nil || textInputNode.attributedText!.length == 0 || textInputNode.selectedRange.length == 0 { return ASEditableTextNodeTargetForAction(target: nil) diff --git a/submodules/TelegramUI/Sources/ContactMultiselectionController.swift b/submodules/TelegramUI/Sources/ContactMultiselectionController.swift index 26ffc272b3..a16b3d5bbc 100644 --- a/submodules/TelegramUI/Sources/ContactMultiselectionController.swift +++ b/submodules/TelegramUI/Sources/ContactMultiselectionController.swift @@ -204,8 +204,8 @@ class ContactMultiselectionControllerImpl: ViewController, ContactMultiselection self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: self.presentationData.strings.Common_Cancel, style: .plain, target: self, action: #selector(cancelPressed)) self.navigationItem.rightBarButtonItem = self.rightNavigationButton rightNavigationButton.isEnabled = false - case let .chatSelection(chatSelection): - self.titleView.title = CounterContollerTitle(title: chatSelection.title, counter: "") + case let .chatSelection(title, _, _, _): + self.titleView.title = CounterContollerTitle(title: title, counter: "") let rightNavigationButton = UIBarButtonItem(title: self.presentationData.strings.Common_Done, style: .done, target: self, action: #selector(self.rightNavigationButtonPressed)) self.rightNavigationButton = rightNavigationButton self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: self.presentationData.strings.Common_Cancel, style: .plain, target: self, action: #selector(cancelPressed)) diff --git a/submodules/TelegramUI/Sources/CreateGroupController.swift b/submodules/TelegramUI/Sources/CreateGroupController.swift index 0df811dd31..d0f04d282b 100644 --- a/submodules/TelegramUI/Sources/CreateGroupController.swift +++ b/submodules/TelegramUI/Sources/CreateGroupController.swift @@ -488,7 +488,6 @@ public func createGroupControllerImpl(context: AccountContext, peerIds: [PeerId] return .complete() } |> mapToSignal { _ -> Signal in - return .complete() } |> then(.single(peerId)) } else { diff --git a/submodules/TelegramUI/Sources/DeclareEncodables.swift b/submodules/TelegramUI/Sources/DeclareEncodables.swift index 444cfa1312..05d4689baa 100644 --- a/submodules/TelegramUI/Sources/DeclareEncodables.swift +++ b/submodules/TelegramUI/Sources/DeclareEncodables.swift @@ -14,49 +14,49 @@ import LocationUI import ChatInterfaceState private var telegramUIDeclaredEncodables: Void = { - declareEncodable(InAppNotificationSettings.self, f: { InAppNotificationSettings(decoder: $0) }) + //declareEncodable(InAppNotificationSettings.self, f: { InAppNotificationSettings(decoder: $0) }) declareEncodable(VideoLibraryMediaResource.self, f: { VideoLibraryMediaResource(decoder: $0) }) declareEncodable(LocalFileVideoMediaResource.self, f: { LocalFileVideoMediaResource(decoder: $0) }) declareEncodable(LocalFileGifMediaResource.self, f: { LocalFileGifMediaResource(decoder: $0) }) declareEncodable(PhotoLibraryMediaResource.self, f: { PhotoLibraryMediaResource(decoder: $0) }) - declareEncodable(PresentationPasscodeSettings.self, f: { PresentationPasscodeSettings(decoder: $0) }) - declareEncodable(MediaAutoDownloadSettings.self, f: { MediaAutoDownloadSettings(decoder: $0) }) - declareEncodable(AutomaticMediaDownloadSettings.self, f: { AutomaticMediaDownloadSettings(decoder: $0) }) - declareEncodable(GeneratedMediaStoreSettings.self, f: { GeneratedMediaStoreSettings(decoder: $0) }) - declareEncodable(PresentationThemeSettings.self, f: { PresentationThemeSettings(decoder: $0) }) + //declareEncodable(PresentationPasscodeSettings.self, f: { PresentationPasscodeSettings(decoder: $0) }) + //declareEncodable(MediaAutoDownloadSettings.self, f: { MediaAutoDownloadSettings(decoder: $0) }) + //declareEncodable(AutomaticMediaDownloadSettings.self, f: { AutomaticMediaDownloadSettings(decoder: $0) }) + //declareEncodable(GeneratedMediaStoreSettings.self, f: { GeneratedMediaStoreSettings(decoder: $0) }) + //declareEncodable(PresentationThemeSettings.self, f: { PresentationThemeSettings(decoder: $0) }) declareEncodable(ApplicationSpecificBoolNotice.self, f: { ApplicationSpecificBoolNotice(decoder: $0) }) declareEncodable(ApplicationSpecificVariantNotice.self, f: { ApplicationSpecificVariantNotice(decoder: $0) }) declareEncodable(ApplicationSpecificCounterNotice.self, f: { ApplicationSpecificCounterNotice(decoder: $0) }) declareEncodable(ApplicationSpecificTimestampNotice.self, f: { ApplicationSpecificTimestampNotice(decoder: $0) }) declareEncodable(ApplicationSpecificInt64ArrayNotice.self, f: { ApplicationSpecificInt64ArrayNotice(decoder: $0) }) - declareEncodable(CallListSettings.self, f: { CallListSettings(decoder: $0) }) - declareEncodable(VoiceCallSettings.self, f: { VoiceCallSettings(decoder: $0) }) - declareEncodable(ExperimentalSettings.self, f: { ExperimentalSettings(decoder: $0) }) - declareEncodable(ExperimentalUISettings.self, f: { ExperimentalUISettings(decoder: $0) }) - declareEncodable(MusicPlaybackSettings.self, f: { MusicPlaybackSettings(decoder: $0) }) + //declareEncodable(CallListSettings.self, f: { CallListSettings(decoder: $0) }) + //declareEncodable(VoiceCallSettings.self, f: { VoiceCallSettings(decoder: $0) }) + //declareEncodable(ExperimentalSettings.self, f: { ExperimentalSettings(decoder: $0) }) + //declareEncodable(ExperimentalUISettings.self, f: { ExperimentalUISettings(decoder: $0) }) + //declareEncodable(MusicPlaybackSettings.self, f: { MusicPlaybackSettings(decoder: $0) }) declareEncodable(ICloudFileResource.self, f: { ICloudFileResource(decoder: $0) }) - declareEncodable(MediaInputSettings.self, f: { MediaInputSettings(decoder: $0) }) - declareEncodable(ContactSynchronizationSettings.self, f: { ContactSynchronizationSettings(decoder: $0) }) + //declareEncodable(MediaInputSettings.self, f: { MediaInputSettings(decoder: $0) }) + //declareEncodable(ContactSynchronizationSettings.self, f: { ContactSynchronizationSettings(decoder: $0) }) declareEncodable(CachedChannelAdminRanks.self, f: { CachedChannelAdminRanks(decoder: $0) }) - declareEncodable(StickerSettings.self, f: { StickerSettings(decoder: $0) }) - declareEncodable(InstantPagePresentationSettings.self, f: { InstantPagePresentationSettings(decoder: $0) }) + //declareEncodable(StickerSettings.self, f: { StickerSettings(decoder: $0) }) + //declareEncodable(InstantPagePresentationSettings.self, f: { InstantPagePresentationSettings(decoder: $0) }) declareEncodable(InstantPageStoredState.self, f: { InstantPageStoredState(decoder: $0) }) declareEncodable(InstantPageStoredDetailsState.self, f: { InstantPageStoredDetailsState(decoder: $0) }) declareEncodable(CachedInstantPage.self, f: { CachedInstantPage(decoder: $0) }) declareEncodable(CachedWallpaper.self, f: { CachedWallpaper(decoder: $0) }) - declareEncodable(WatchPresetSettings.self, f: { WatchPresetSettings(decoder: $0) }) - declareEncodable(WebSearchSettings.self, f: { WebSearchSettings(decoder: $0) }) + //declareEncodable(WatchPresetSettings.self, f: { WatchPresetSettings(decoder: $0) }) + //declareEncodable(WebSearchSettings.self, f: { WebSearchSettings(decoder: $0) }) declareEncodable(RecentWebSearchQueryItem.self, f: { RecentWebSearchQueryItem(decoder: $0) }) declareEncodable(RecentWallpaperSearchQueryItem.self, f: { RecentWallpaperSearchQueryItem(decoder: $0) }) declareEncodable(RecentSettingsSearchQueryItem.self, f: { RecentSettingsSearchQueryItem(decoder: $0) }) - declareEncodable(VoipDerivedState.self, f: { VoipDerivedState(decoder: $0) }) - declareEncodable(ChatArchiveSettings.self, f: { ChatArchiveSettings(decoder: $0) }) + //declareEncodable(VoipDerivedState.self, f: { VoipDerivedState(decoder: $0) }) + //declareEncodable(ChatArchiveSettings.self, f: { ChatArchiveSettings(decoder: $0) }) declareEncodable(MediaPlaybackStoredState.self, f: { MediaPlaybackStoredState(decoder: $0) }) - declareEncodable(WebBrowserSettings.self, f: { WebBrowserSettings(decoder: $0) }) - declareEncodable(IntentsSettings.self, f: { IntentsSettings(decoder: $0) }) + //declareEncodable(WebBrowserSettings.self, f: { WebBrowserSettings(decoder: $0) }) + //declareEncodable(IntentsSettings.self, f: { IntentsSettings(decoder: $0) }) declareEncodable(CachedGeocode.self, f: { CachedGeocode(decoder: $0) }) - declareEncodable(ChatListFilterSettings.self, f: { ChatListFilterSettings(decoder: $0) }) - declareEncodable(WidgetSettings.self, f: { WidgetSettings(decoder: $0) }) + //declareEncodable(ChatListFilterSettings.self, f: { ChatListFilterSettings(decoder: $0) }) + //declareEncodable(WidgetSettings.self, f: { WidgetSettings(decoder: $0) }) return }() diff --git a/submodules/TelegramUI/Sources/DrawingStickersScreen.swift b/submodules/TelegramUI/Sources/DrawingStickersScreen.swift index 3dbcb071f0..4216d2b477 100644 --- a/submodules/TelegramUI/Sources/DrawingStickersScreen.swift +++ b/submodules/TelegramUI/Sources/DrawingStickersScreen.swift @@ -954,7 +954,7 @@ private final class DrawingStickersScreenNode: ViewControllerTracingNode { func updateLayout(width: CGFloat, topInset: CGFloat, leftInset: CGFloat, rightInset: CGFloat, bottomInset: CGFloat, standardInputHeight: CGFloat, inputHeight: CGFloat, maximumHeight: CGFloat, inputPanelHeight: CGFloat, transition: ContainedViewLayoutTransition, deviceMetrics: DeviceMetrics, isVisible: Bool) -> (CGFloat, CGFloat) { let searchMode: ChatMediaInputSearchMode? = nil - let displaySearch = false + let displaySearch = !"".isEmpty //silence warning let separatorHeight = max(UIScreenPixel, 1.0 - UIScreenPixel) let topPanelHeight: CGFloat = 56.0 let panelHeight: CGFloat diff --git a/submodules/TelegramUI/Sources/EmojiResources.swift b/submodules/TelegramUI/Sources/EmojiResources.swift index 849c21353f..a16daab35d 100644 --- a/submodules/TelegramUI/Sources/EmojiResources.swift +++ b/submodules/TelegramUI/Sources/EmojiResources.swift @@ -334,7 +334,9 @@ func fetchEmojiSpriteResource(account: Account, resource: EmojiSpriteResource) - if buffer.data.count < range.count { buffer.data.count = range.count } - buffer.data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + buffer.data.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + data.copyBytes(to: bytes, from: range) } } @@ -343,7 +345,9 @@ func fetchEmojiSpriteResource(account: Account, resource: EmojiSpriteResource) - if buffer.data.count < resourceOffset + range.count { buffer.data.count = resourceOffset + range.count } - buffer.data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in + buffer.data.withUnsafeMutableBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + data.copyBytes(to: bytes.advanced(by: resourceOffset), from: range) } } diff --git a/submodules/TelegramUI/Sources/FetchManager.swift b/submodules/TelegramUI/Sources/FetchManager.swift index 9647c451b7..028bf0d04f 100644 --- a/submodules/TelegramUI/Sources/FetchManager.swift +++ b/submodules/TelegramUI/Sources/FetchManager.swift @@ -24,9 +24,10 @@ private struct FetchManagerLocationEntryId: Hashable { } return true } - - var hashValue: Int { - return self.resourceId.hashValue &* 31 &+ self.locationKey.hashValue + + func hash(into hasher: inout Hasher) { + hasher.combine(self.resourceId.hashValue) + hasher.combine(self.locationKey) } } @@ -221,7 +222,6 @@ private final class FetchManagerCategoryContext { return storeDownloadedMedia(storeManager: storeManager, media: mediaReference, peerType: peerType) |> castError(FetchResourceError.self) |> mapToSignal { _ -> Signal in - return .complete() } |> then(.single(type)) } @@ -349,7 +349,7 @@ private final class FetchManagerCategoryContext { if isVideoPreload { activeContext.disposable = (preloadVideoResource(postbox: self.postbox, resourceReference: entry.resourceReference, duration: 4.0) |> castError(FetchResourceError.self) - |> map { _ -> FetchResourceSourceType in return .local } + |> map { _ -> FetchResourceSourceType in } |> then(.single(.local)) |> deliverOnMainQueue).start(next: { _ in entryCompleted(topEntryId) @@ -362,7 +362,6 @@ private final class FetchManagerCategoryContext { return storeDownloadedMedia(storeManager: storeManager, media: mediaReference, peerType: peerType) |> castError(FetchResourceError.self) |> mapToSignal { _ -> Signal in - return .complete() } |> then(.single(type)) } diff --git a/submodules/TelegramUI/Sources/FetchVideoMediaResource.swift b/submodules/TelegramUI/Sources/FetchVideoMediaResource.swift index 99d89c1a8e..3478ce8392 100644 --- a/submodules/TelegramUI/Sources/FetchVideoMediaResource.swift +++ b/submodules/TelegramUI/Sources/FetchVideoMediaResource.swift @@ -210,7 +210,7 @@ public func fetchVideoLibraryMediaResource(account: Account, resource: VideoLibr return account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> take(1) |> map { view in - return view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + return view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue } |> castError(MediaResourceDataFetchError.self) |> mapToSignal { appConfiguration -> Signal in @@ -323,7 +323,7 @@ func fetchLocalFileVideoMediaResource(account: Account, resource: LocalFileVideo return account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> take(1) |> map { view in - return view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + return view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue } |> castError(MediaResourceDataFetchError.self) |> mapToSignal { appConfiguration -> Signal in diff --git a/submodules/TelegramUI/Sources/HorizontalListContextResultsChatInputContextPanelNode.swift b/submodules/TelegramUI/Sources/HorizontalListContextResultsChatInputContextPanelNode.swift index 14f0660861..169d75d239 100644 --- a/submodules/TelegramUI/Sources/HorizontalListContextResultsChatInputContextPanelNode.swift +++ b/submodules/TelegramUI/Sources/HorizontalListContextResultsChatInputContextPanelNode.swift @@ -14,9 +14,9 @@ import ContextUI private struct ChatContextResultStableId: Hashable { let result: ChatContextResult - - var hashValue: Int { - return result.id.hashValue + + func hash(into hasher: inout Hasher) { + hasher.combine(result.id.hashValue) } static func ==(lhs: ChatContextResultStableId, rhs: ChatContextResultStableId) -> Bool { diff --git a/submodules/TelegramUI/Sources/HorizontalStickerGridItem.swift b/submodules/TelegramUI/Sources/HorizontalStickerGridItem.swift index 1da6c74a9c..4e7f9e15d7 100755 --- a/submodules/TelegramUI/Sources/HorizontalStickerGridItem.swift +++ b/submodules/TelegramUI/Sources/HorizontalStickerGridItem.swift @@ -229,17 +229,10 @@ final class HorizontalStickerGridItemNode: GridItemNode { if self.currentIsPreviewing != isPreviewing { self.currentIsPreviewing = isPreviewing - - if isPreviewing { - self.layer.sublayerTransform = CATransform3DMakeScale(0.8, 0.8, 1.0) - if animated { - self.layer.animateSpring(from: 1.0 as NSNumber, to: 0.8 as NSNumber, keyPath: "sublayerTransform.scale", duration: 0.4) - } - } else { - self.layer.sublayerTransform = CATransform3DIdentity - if animated { - self.layer.animateSpring(from: 0.8 as NSNumber, to: 1.0 as NSNumber, keyPath: "sublayerTransform.scale", duration: 0.5) - } + + self.layer.sublayerTransform = CATransform3DIdentity + if animated { + self.layer.animateSpring(from: 0.8 as NSNumber, to: 1.0 as NSNumber, keyPath: "sublayerTransform.scale", duration: 0.5) } } } diff --git a/submodules/TelegramUI/Sources/ID3ArtworkReader.swift b/submodules/TelegramUI/Sources/ID3ArtworkReader.swift index 24f0f9f214..0fdc8aef04 100644 --- a/submodules/TelegramUI/Sources/ID3ArtworkReader.swift +++ b/submodules/TelegramUI/Sources/ID3ArtworkReader.swift @@ -99,8 +99,8 @@ private class DataStream { guard self.position + count <= self.data.count else { return nil } - let value = self.data.subdata(in: self.position ..< self.position + count).withUnsafeBytes { (pointer: UnsafePointer) -> T in - return pointer.pointee + let value = self.data.subdata(in: self.position ..< self.position + count).withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> T in + return pointer.baseAddress!.assumingMemoryBound(to: T.self).pointee } self.position += count return value diff --git a/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift b/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift index b6863bb552..543a1e6089 100644 --- a/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift +++ b/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift @@ -68,7 +68,7 @@ func sharedAccountInfos(accountManager: AccountManager take(1) |> mapToSignal { sharedData, accounts -> Signal in - let proxySettings = sharedData.entries[SharedDataKeys.proxySettings] as? ProxySettings + let proxySettings = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) let proxy = proxySettings?.effectiveActiveServer.flatMap { proxyServer -> AccountProxyConnection? in var username: String? var password: String? diff --git a/submodules/TelegramUI/Sources/ManagedAudioRecorder.swift b/submodules/TelegramUI/Sources/ManagedAudioRecorder.swift index 8e806c494d..62c84ba93a 100644 --- a/submodules/TelegramUI/Sources/ManagedAudioRecorder.swift +++ b/submodules/TelegramUI/Sources/ManagedAudioRecorder.swift @@ -234,7 +234,9 @@ final class ManagedAudioRecorderContext { var blockBuffer: CMBlockBuffer? let bytes = malloc(takeRange.count)! - toneData.withUnsafeBytes { (dataBytes: UnsafePointer) -> Void in + toneData.withUnsafeBytes { rawDataBytes -> Void in + let dataBytes = rawDataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) + memcpy(bytes, dataBytes.advanced(by: takeRange.lowerBound), takeRange.count) } let status = CMBlockBufferCreateWithMemoryBlock(allocator: nil, memoryBlock: bytes, blockLength: takeRange.count, blockAllocator: nil, customBlockSource: nil, offsetToData: 0, dataLength: takeRange.count, flags: 0, blockBufferOut: &blockBuffer) @@ -502,7 +504,9 @@ final class ManagedAudioRecorderContext { if audioBuffer.count != 0 { let takenBytes = min(self.audioBuffer.count, encoderPacketSizeInBytes - currentEncoderPacketSize) if takenBytes != 0 { - self.audioBuffer.withUnsafeBytes { (bytes: UnsafePointer) -> Void in + self.audioBuffer.withUnsafeBytes { rawBytes -> Void in + let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self) + memcpy(currentEncoderPacket.advanced(by: currentEncoderPacketSize), bytes, takenBytes) } self.audioBuffer.replaceSubrange(0 ..< takenBytes, with: Data()) @@ -511,9 +515,8 @@ final class ManagedAudioRecorderContext { } else if bufferOffset < Int(buffer.mDataByteSize) { let takenBytes = min(Int(buffer.mDataByteSize) - bufferOffset, encoderPacketSizeInBytes - currentEncoderPacketSize) if takenBytes != 0 { - self.audioBuffer.withUnsafeBytes { (bytes: UnsafePointer) -> Void in - memcpy(currentEncoderPacket.advanced(by: currentEncoderPacketSize), buffer.mData?.advanced(by: bufferOffset), takenBytes) - } + memcpy(currentEncoderPacket.advanced(by: currentEncoderPacketSize), buffer.mData?.advanced(by: bufferOffset), takenBytes) + bufferOffset += takenBytes currentEncoderPacketSize += takenBytes } @@ -562,7 +565,9 @@ final class ManagedAudioRecorderContext { let compressedSampleCount = self.compressedWaveformSamples.count / 2 if compressedSampleCount == 200 { - self.compressedWaveformSamples.withUnsafeMutableBytes { (compressedSamples: UnsafeMutablePointer) -> Void in + self.compressedWaveformSamples.withUnsafeMutableBytes { rawCompressedSamples -> Void in + let compressedSamples = rawCompressedSamples.baseAddress!.assumingMemoryBound(to: Int16.self) + for i in 0 ..< 100 { let maxSample = Int64(max(compressedSamples[i * 2 + 0], compressedSamples[i * 2 + 1])) compressedSamples[i] = Int16(maxSample) @@ -604,7 +609,9 @@ final class ManagedAudioRecorderContext { var waveform: Data? let count = self.compressedWaveformSamples.count / 2 - self.compressedWaveformSamples.withUnsafeMutableBytes { (samples: UnsafeMutablePointer) -> Void in + self.compressedWaveformSamples.withUnsafeMutableBytes { rawSamples -> Void in + let samples = rawSamples.baseAddress!.assumingMemoryBound(to: Int16.self) + for i in 0 ..< count { let sample = samples[i] let index = i * 100 / count diff --git a/submodules/TelegramUI/Sources/ManagedDiceAnimationNode.swift b/submodules/TelegramUI/Sources/ManagedDiceAnimationNode.swift index 0a5a2cdb37..ceaef5094e 100644 --- a/submodules/TelegramUI/Sources/ManagedDiceAnimationNode.swift +++ b/submodules/TelegramUI/Sources/ManagedDiceAnimationNode.swift @@ -133,7 +133,7 @@ final class ManagedDiceAnimationNode: ManagedAnimationNode, GenericAnimatedStick self.configuration.set(self.context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { preferencesView -> InteractiveEmojiConfiguration? in - let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + let appConfiguration: AppConfiguration = preferencesView.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue return InteractiveEmojiConfiguration.with(appConfiguration: appConfiguration) }) self.emojis.set(context.engine.stickers.loadedStickerPack(reference: .dice(emoji), forceActualized: false) diff --git a/submodules/TelegramUI/Sources/MediaManager.swift b/submodules/TelegramUI/Sources/MediaManager.swift index 0b94cf60fd..f4abb6e120 100644 --- a/submodules/TelegramUI/Sources/MediaManager.swift +++ b/submodules/TelegramUI/Sources/MediaManager.swift @@ -479,7 +479,7 @@ public final class MediaManagerImpl: NSObject, MediaManager { inputData = self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.musicPlaybackSettings]) |> take(1) |> mapToSignal { sharedData -> Signal<(Account, SharedMediaPlaylist, MusicPlaybackSettings, MediaPlaybackStoredState?)?, NoError> in - let settings = (sharedData.entries[ApplicationSpecificSharedDataKeys.musicPlaybackSettings] as? MusicPlaybackSettings) ?? MusicPlaybackSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.musicPlaybackSettings]?.get(MusicPlaybackSettings.self) ?? MusicPlaybackSettings.defaultSettings if let location = playlist.location as? PeerMessagesPlaylistLocation, let messageId = location.messageId { return mediaPlaybackStoredState(postbox: account.postbox, messageId: messageId) diff --git a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift index 84c8380770..e8dc04e5a3 100644 --- a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift +++ b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift @@ -106,7 +106,7 @@ func openResolvedUrlImpl(_ resolvedUrl: ResolvedUrl, context: AccountContext, ur } case let .stickerPack(name): dismissInput() - if false { + /*if false { var mainStickerPack: StickerPackReference? var stickerPacks: [StickerPackReference] = [] if let message = contentContext as? Message { @@ -140,10 +140,10 @@ func openResolvedUrlImpl(_ resolvedUrl: ResolvedUrl, context: AccountContext, ur let controller = StickerPackScreen(context: context, mainStickerPack: mainStickerPack, stickerPacks: stickerPacks, parentNavigationController: navigationController, sendSticker: sendSticker) present(controller, nil) } - } else { + } else {*/ let controller = StickerPackScreen(context: context, mainStickerPack: .name(name), stickerPacks: [.name(name)], parentNavigationController: navigationController, sendSticker: sendSticker) present(controller, nil) - } + //} case let .instantView(webpage, anchor): navigationController?.pushViewController(InstantPageController(context: context, webPage: webpage, sourcePeerType: .channel, anchor: anchor)) case let .join(link): diff --git a/submodules/TelegramUI/Sources/OpenUrl.swift b/submodules/TelegramUI/Sources/OpenUrl.swift index 5114643757..a53cf2e052 100644 --- a/submodules/TelegramUI/Sources/OpenUrl.swift +++ b/submodules/TelegramUI/Sources/OpenUrl.swift @@ -149,7 +149,7 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur } if let parsed = URL(string: urlWithScheme) { parsedUrlValue = parsed - } else if let encoded = (urlWithScheme as NSString).addingPercentEscapes(using: String.Encoding.utf8.rawValue), let parsed = URL(string: encoded) { + } else if let encoded = (urlWithScheme as NSString).addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed), let parsed = URL(string: encoded) { parsedUrlValue = parsed } @@ -710,14 +710,14 @@ func openExternalUrlImpl(context: AccountContext, urlContext: OpenURLContext, ur let settings = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.webBrowserSettings, ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]), context.sharedContext.accountManager.accessChallengeData()) |> take(1) |> map { sharedData, accessChallengeData -> WebBrowserSettings in - let passcodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings] as? PresentationPasscodeSettings ?? PresentationPasscodeSettings.defaultSettings + let passcodeSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.presentationPasscodeSettings]?.get(PresentationPasscodeSettings.self) ?? PresentationPasscodeSettings.defaultSettings if accessChallengeData.data.isLockable { if passcodeSettings.autolockTimeout != nil { return WebBrowserSettings(defaultWebBrowser: "Safari") } } - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings] as? WebBrowserSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webBrowserSettings]?.get(WebBrowserSettings.self) { return current } else { return WebBrowserSettings.defaultSettings diff --git a/submodules/TelegramUI/Sources/PeerInfo/Panes/PeerInfoListPaneNode.swift b/submodules/TelegramUI/Sources/PeerInfo/Panes/PeerInfoListPaneNode.swift index 5b7ecb4ce0..347c63d61a 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/Panes/PeerInfoListPaneNode.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/Panes/PeerInfoListPaneNode.swift @@ -223,10 +223,10 @@ final class PeerInfoListPaneNode: ASDisplayNode, PeerInfoPaneNode { return } let _ = (strongSelf.context.sharedContext.accountManager.transaction { transaction -> AudioPlaybackRate in - let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings) as? MusicPlaybackSettings ?? MusicPlaybackSettings.defaultSettings + let settings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings)?.get(MusicPlaybackSettings.self) ?? MusicPlaybackSettings.defaultSettings transaction.updateSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings, { _ in - return settings.withUpdatedVoicePlaybackRate(rate) + return PreferencesEntry(settings.withUpdatedVoicePlaybackRate(rate)) }) return rate } diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoData.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoData.swift index bfe3e5513e..668a68aba0 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoData.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoData.swift @@ -406,15 +406,15 @@ func peerInfoScreenSettingsData(context: AccountContext, peerId: PeerId, account let (notificationExceptions, notificationsAuthorizationStatus, notificationsWarningSuppressed) = notifications let (featuredStickerPacks, archivedStickerPacks) = stickerPacks - let proxySettings: ProxySettings = sharedPreferences.entries[SharedDataKeys.proxySettings] as? ProxySettings ?? ProxySettings.defaultSettings - let inAppNotificationSettings: InAppNotificationSettings = sharedPreferences.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings ?? InAppNotificationSettings.defaultSettings + let proxySettings: ProxySettings = sharedPreferences.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) ?? ProxySettings.defaultSettings + let inAppNotificationSettings: InAppNotificationSettings = sharedPreferences.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) ?? InAppNotificationSettings.defaultSettings let unreadTrendingStickerPacks = featuredStickerPacks.reduce(0, { count, item -> Int in return item.unread ? count + 1 : count }) var enableQRLogin = false - if let appConfiguration = accountPreferences.values[PreferencesKeys.appConfiguration] as? AppConfiguration, let data = appConfiguration.data, let enableQR = data["qr_login_camera"] as? Bool, enableQR { + if let appConfiguration = accountPreferences.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self), let data = appConfiguration.data, let enableQR = data["qr_login_camera"] as? Bool, enableQR { enableQRLogin = true } @@ -564,7 +564,7 @@ func peerInfoScreenData(context: AccountContext, peerId: PeerId, strings: Presen |> map { peerView, availablePanes, combinedView, status -> PeerInfoScreenData in var globalNotificationSettings: GlobalNotificationSettings = .defaultSettings if let preferencesView = combinedView.views[globalNotificationsKey] as? PreferencesView { - if let settings = preferencesView.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = preferencesView.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { globalNotificationSettings = settings } } @@ -631,7 +631,7 @@ func peerInfoScreenData(context: AccountContext, peerId: PeerId, strings: Presen |> map { peerView, availablePanes, combinedView, status, currentInvitationsContext, invitations -> PeerInfoScreenData in var globalNotificationSettings: GlobalNotificationSettings = .defaultSettings if let preferencesView = combinedView.views[globalNotificationsKey] as? PreferencesView { - if let settings = preferencesView.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = preferencesView.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { globalNotificationSettings = settings } } @@ -779,7 +779,7 @@ func peerInfoScreenData(context: AccountContext, peerId: PeerId, strings: Presen |> map { peerView, availablePanes, combinedView, status, membersData, currentInvitationsContext, invitations -> PeerInfoScreenData in var globalNotificationSettings: GlobalNotificationSettings = .defaultSettings if let preferencesView = combinedView.views[globalNotificationsKey] as? PreferencesView { - if let settings = preferencesView.values[PreferencesKeys.globalNotifications] as? GlobalNotificationSettings { + if let settings = preferencesView.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) { globalNotificationSettings = settings } } @@ -888,8 +888,8 @@ func availableActionsForMemberOfPeer(accountPeerId: PeerId, peer: Peer?, member: switch channelMember.participant { case .creator: break - case let .member(member): - if let adminInfo = member.adminInfo { + case let .member(_, _, adminInfo, _, _): + if let adminInfo = adminInfo { if adminInfo.promotedBy == accountPeerId { if !channel.flags.contains(.isGigagroup) { result.insert(.restrict) @@ -920,8 +920,8 @@ func availableActionsForMemberOfPeer(accountPeerId: PeerId, peer: Peer?, member: result.insert(.promote) case .admin: switch member { - case let .legacyGroupMember(legacyGroupMember): - if legacyGroupMember.invitedBy == accountPeerId { + case let .legacyGroupMember(_, _, invitedBy, _): + if invitedBy == accountPeerId { result.insert(.restrict) result.insert(.promote) } @@ -932,8 +932,8 @@ func availableActionsForMemberOfPeer(accountPeerId: PeerId, peer: Peer?, member: } case .member: switch member { - case let .legacyGroupMember(legacyGroupMember): - if legacyGroupMember.invitedBy == accountPeerId { + case let .legacyGroupMember(_, _, invitedBy, _): + if invitedBy == accountPeerId { result.insert(.restrict) } case .channelMember: diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift index 758a112568..12f4218ebb 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoHeaderNode.swift @@ -374,7 +374,7 @@ final class PeerInfoAvatarTransformContainerNode: ASDisplayNode { if peer.isDeleted { overrideImage = .deletedIcon } else if let previousItem = previousItem, item == nil { - if case let .image(image) = previousItem, let rep = image.1.last { + if case let .image(_, representations, _, _) = previousItem, let rep = representations.last { self.removedPhotoResourceIds.insert(rep.representation.resource.id.uniqueId) } overrideImage = AvatarNodeImageOverride.none @@ -596,9 +596,9 @@ final class PeerInfoEditingAvatarOverlayNode: ASDisplayNode { } } - transition.updateAlpha(node: self.updatingAvatarOverlay, alpha: overlayHidden ? 0.0 : 1.0) + transition.updateAlpha(node: self.updatingAvatarOverlay, alpha: 1.0) } else { - let targetOverlayAlpha: CGFloat = overlayHidden ? 0.0 : 1.0 + let targetOverlayAlpha: CGFloat = 0.0 if self.updatingAvatarOverlay.alpha != targetOverlayAlpha { let update = { self.statusNode.transitionToState(.none) @@ -679,7 +679,7 @@ final class PeerInfoEditingAvatarNode: ASDisplayNode { if canEditPeerInfo(context: self.context, peer: peer), peer.profileImageRepresentations.isEmpty { overrideImage = .editAvatarIcon } else if let previousItem = previousItem, item == nil { - if case let .image(image) = previousItem, let rep = image.1.last { + if case let .image(_, representations, _, _) = previousItem, let rep = representations.last { self.removedPhotoResourceIds.insert(rep.representation.resource.id.uniqueId) } overrideImage = AvatarNodeImageOverride.none diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoMembers.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoMembers.swift index f6cc4942c8..5a870b205c 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoMembers.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoMembers.swift @@ -20,8 +20,8 @@ enum PeerInfoMember: Equatable { switch self { case let .channelMember(channelMember): return channelMember.peer.id - case let .legacyGroupMember(legacyGroupMember): - return legacyGroupMember.peer.peerId + case let .legacyGroupMember(peer, _, _, _): + return peer.peerId case let .account(peer): return peer.peerId } @@ -31,8 +31,8 @@ enum PeerInfoMember: Equatable { switch self { case let .channelMember(channelMember): return channelMember.peer - case let .legacyGroupMember(legacyGroupMember): - return legacyGroupMember.peer.peers[legacyGroupMember.peer.peerId]! + case let .legacyGroupMember(peer, _, _, _): + return peer.peers[peer.peerId]! case let .account(peer): return peer.peers[peer.peerId]! } @@ -42,8 +42,8 @@ enum PeerInfoMember: Equatable { switch self { case let .channelMember(channelMember): return channelMember.presences[channelMember.peer.id] as? TelegramUserPresence - case let .legacyGroupMember(legacyGroupMember): - return legacyGroupMember.presence + case let .legacyGroupMember(_, _, _, presence): + return presence case .account: return nil } @@ -55,15 +55,15 @@ enum PeerInfoMember: Equatable { switch channelMember.participant { case .creator: return .creator - case let .member(member): - if member.adminInfo != nil { + case let .member(_, _, adminInfo, _, _): + if adminInfo != nil { return .admin } else { return .member } } - case let .legacyGroupMember(legacyGroupMember): - return legacyGroupMember.role + case let .legacyGroupMember(_, role, _, _): + return role case .account: return .member } @@ -73,10 +73,10 @@ enum PeerInfoMember: Equatable { switch self { case let .channelMember(channelMember): switch channelMember.participant { - case let .creator(creator): - return creator.rank - case let .member(member): - return member.rank + case let .creator(_, _, rank): + return rank + case let .member(_, _, _, _, rank): + return rank } case .legacyGroupMember: return nil @@ -185,12 +185,12 @@ private final class PeerInfoMembersContextImpl { case .creator: role = .creator invitedBy = nil - case let .admin(admin): + case let .admin(_, invitedByValue, _): role = .admin - invitedBy = admin.invitedBy - case let .member(member): + invitedBy = invitedByValue + case let .member(_, invitedByValue, _): role = .member - invitedBy = member.invitedBy + invitedBy = invitedByValue } unsortedMembers.append(.legacyGroupMember(peer: RenderedPeer(peer: peer), role: role, invitedBy: invitedBy, presence: view.peerPresences[participant.peerId] as? TelegramUserPresence)) } @@ -249,9 +249,7 @@ private final class PeerInfoMembersContextImpl { self.pushState() disposable.set((signal - |> deliverOn(self.queue)).start(error: { _ in - completed() - }, completed: { + |> deliverOn(self.queue)).start(completed: { completed() })) } diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift index a155558446..f3d1768e8c 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift @@ -2505,14 +2505,7 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD strongSelf.controller?.present(statusController, in: .window(.root)) } strongSelf.activeActionDisposable.set((combineLatest(updateNameSignal, updateBioSignal) |> deliverOnMainQueue - |> deliverOnMainQueue).start(error: { _ in - dismissStatus?() - - guard let strongSelf = self else { - return - } - strongSelf.headerNode.navigationButtonContainer.performAction?(.cancel) - }, completed: { + |> deliverOnMainQueue).start(completed: { dismissStatus?() guard let strongSelf = self else { @@ -2812,8 +2805,8 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD var currentIsVideo = false let item = strongSelf.headerNode.avatarListNode.listContainerNode.currentItemNode?.item - if let item = item, case let .image(image) = item { - currentIsVideo = !image.2.isEmpty + if let item = item, case let .image(_, _, videoRepresentations, _) = item { + currentIsVideo = !videoRepresentations.isEmpty } let items: [ContextMenuItem] = [ @@ -4114,7 +4107,7 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD let peerId = self.peerId let _ = (self.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 + let globalSettings: GlobalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) } |> deliverOnMainQueue).start(next: { [weak self] peerSettings, globalSettings in @@ -4148,7 +4141,7 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD let peerId = self.peerId let _ = (self.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 + let globalSettings: GlobalNotificationSettings = transaction.getPreferencesEntry(key: PreferencesKeys.globalNotifications)?.get(GlobalNotificationSettings.self) ?? GlobalNotificationSettings.defaultSettings return (peerSettings, globalSettings) } |> deliverOnMainQueue).start(next: { [weak self] peerSettings, globalSettings in @@ -5232,8 +5225,8 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD var currentIsVideo = false let item = self.headerNode.avatarListNode.listContainerNode.currentItemNode?.item - if let item = item, case let .image(image) = item { - currentIsVideo = !image.2.isEmpty + if let item = item, case let .image(_, _, videoRepresentations, _) = item { + currentIsVideo = !videoRepresentations.isEmpty } let peerId = self.peerId @@ -6575,7 +6568,7 @@ public final class PeerInfoScreenImpl: ViewController, PeerInfoScreen { let notificationsFromAllAccounts = self.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.inAppNotificationSettings]) |> map { sharedData -> Bool in - let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings ?? InAppNotificationSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) ?? InAppNotificationSettings.defaultSettings return settings.displayNotificationsFromAllAccounts } |> distinctUntilChanged diff --git a/submodules/TelegramUI/Sources/PeerSelectionTextInputPanelNode.swift b/submodules/TelegramUI/Sources/PeerSelectionTextInputPanelNode.swift index cfd7f85ebd..fabb3f56d6 100644 --- a/submodules/TelegramUI/Sources/PeerSelectionTextInputPanelNode.swift +++ b/submodules/TelegramUI/Sources/PeerSelectionTextInputPanelNode.swift @@ -12,6 +12,7 @@ import AccountContext import TouchDownGesture import ActivityIndicator import Speak +import ObjCRuntimeUtils private let counterFont = Font.with(size: 14.0, design: .regular, traits: [.monospacedNumbers]) private let minInputFontSize = chatTextInputMinFontSize @@ -706,7 +707,7 @@ class PeerSelectionTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDel } func editableTextNodeTarget(forAction action: Selector) -> ASEditableTextNodeTargetForAction? { - if action == Selector(("_accessibilitySpeak:")) { + if action == makeSelectorFromString("_accessibilitySpeak:") { if case .format = self.inputMenu.state { return ASEditableTextNodeTargetForAction(target: nil) } else if let textInputNode = self.textInputNode, textInputNode.selectedRange.length > 0 { @@ -714,7 +715,7 @@ class PeerSelectionTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDel } else { return ASEditableTextNodeTargetForAction(target: nil) } - } else if action == Selector(("_accessibilitySpeakSpellOut:")) { + } else if action == makeSelectorFromString("_accessibilitySpeakSpellOut:") { if case .format = self.inputMenu.state { return ASEditableTextNodeTargetForAction(target: nil) } else if let textInputNode = self.textInputNode, textInputNode.selectedRange.length > 0 { @@ -723,9 +724,9 @@ class PeerSelectionTextInputPanelNode: ChatInputPanelNode, ASEditableTextNodeDel return ASEditableTextNodeTargetForAction(target: nil) } } - else if action == Selector("_accessibilitySpeakLanguageSelection:") || action == Selector("_accessibilityPauseSpeaking:") || action == Selector("_accessibilitySpeakSentence:") { + else if action == makeSelectorFromString("_accessibilitySpeakLanguageSelection:") || action == makeSelectorFromString("_accessibilityPauseSpeaking:") || action == makeSelectorFromString("_accessibilitySpeakSentence:") { return ASEditableTextNodeTargetForAction(target: nil) - } else if action == Selector(("_showTextStyleOptions:")) { + } else if action == makeSelectorFromString("_showTextStyleOptions:") { if case .general = self.inputMenu.state { if let textInputNode = self.textInputNode, textInputNode.attributedText == nil || textInputNode.attributedText!.length == 0 || textInputNode.selectedRange.length == 0 { return ASEditableTextNodeTargetForAction(target: nil) diff --git a/submodules/TelegramUI/Sources/PeersNearbyManager.swift b/submodules/TelegramUI/Sources/PeersNearbyManager.swift index 300852bdb0..79f01e9cd8 100644 --- a/submodules/TelegramUI/Sources/PeersNearbyManager.swift +++ b/submodules/TelegramUI/Sources/PeersNearbyManager.swift @@ -32,7 +32,7 @@ final class PeersNearbyManagerImpl: PeersNearbyManager { self.preferencesDisposable = (account.postbox.preferencesView(keys: [PreferencesKeys.peersNearby]) |> map { view -> Int32? in - let state = view.values[PreferencesKeys.peersNearby] as? PeersNearbyState ?? .default + let state = view.values[PreferencesKeys.peersNearby]?.get(PeersNearbyState.self) ?? .default return state.visibilityExpires } |> deliverOnMainQueue @@ -97,12 +97,6 @@ final class PeersNearbyManagerImpl: PeersNearbyManager { } private func updateLocation(_ location: CLLocation) { - self.updateDisposable.set(self.engine.peersNearby.updatePeersNearbyVisibility(update: .location(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude), background: true).start(error: { [weak self] _ in - if let strongSelf = self { - let _ = strongSelf.engine.peersNearby.updatePeersNearbyVisibility(update: .invisible, background: false).start() - strongSelf.locationDisposable.set(nil) - strongSelf.updateDisposable.set(nil) - } - })) + self.updateDisposable.set(self.engine.peersNearby.updatePeersNearbyVisibility(update: .location(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude), background: true).start()) } } diff --git a/submodules/TelegramUI/Sources/PollResultsController.swift b/submodules/TelegramUI/Sources/PollResultsController.swift index a6e213ab76..b5f56ded9a 100644 --- a/submodules/TelegramUI/Sources/PollResultsController.swift +++ b/submodules/TelegramUI/Sources/PollResultsController.swift @@ -76,10 +76,10 @@ private enum PollResultsEntry: ItemListNodeEntry { switch self { case .text: return PollResultsSection.text.rawValue - case let .optionPeer(optionPeer): - return PollResultsSection.option(optionPeer.optionId).rawValue - case let .optionExpand(optionExpand): - return PollResultsSection.option(optionExpand.optionId).rawValue + case let .optionPeer(optionId, _, _, _, _, _, _, _, _, _): + return PollResultsSection.option(optionId).rawValue + case let .optionExpand(optionId, _, _, _): + return PollResultsSection.option(optionId).rawValue case .solutionHeader, .solutionText: return PollResultsSection.solution.rawValue } @@ -89,10 +89,10 @@ private enum PollResultsEntry: ItemListNodeEntry { switch self { case .text: return .text - case let .optionPeer(optionPeer): - return .optionPeer(optionPeer.optionId, optionPeer.index) - case let .optionExpand(optionExpand): - return .optionExpand(optionExpand.optionId) + case let .optionPeer(optionId, index, _, _, _, _, _, _, _, _): + return .optionPeer(optionId, index) + case let .optionExpand(optionId, _, _, _): + return .optionExpand(optionId) case .solutionHeader: return .solutionHeader case .solutionText: @@ -129,7 +129,7 @@ private enum PollResultsEntry: ItemListNodeEntry { default: return true } - case let .optionPeer(lhsOptionPeer): + case let .optionPeer(lhsOptionId, lhsIndex, _, _, _, _, _, _, _, _): switch rhs { case .text: return false @@ -137,20 +137,20 @@ private enum PollResultsEntry: ItemListNodeEntry { return false case .solutionText: return false - case let .optionPeer(rhsOptionPeer): - if lhsOptionPeer.optionId == rhsOptionPeer.optionId { - return lhsOptionPeer.index < rhsOptionPeer.index + case let .optionPeer(rhsOptionId, rhsIndex, _, _, _, _, _, _, _, _): + if lhsOptionId == rhsOptionId { + return lhsIndex < rhsIndex } else { - return lhsOptionPeer.optionId < rhsOptionPeer.optionId + return lhsOptionId < rhsOptionId } - case let .optionExpand(rhsOptionExpand): - if lhsOptionPeer.optionId == rhsOptionExpand.optionId { + case let .optionExpand(rhsOptionId, _, _, _): + if lhsOptionId == rhsOptionId { return true } else { - return lhsOptionPeer.optionId < rhsOptionExpand.optionId + return lhsOptionId < rhsOptionId } } - case let .optionExpand(lhsOptionExpand): + case let .optionExpand(lhsOptionId, _, _, _): switch rhs { case .text: return false @@ -158,17 +158,17 @@ private enum PollResultsEntry: ItemListNodeEntry { return false case .solutionText: return false - case let .optionPeer(rhsOptionPeer): - if lhsOptionExpand.optionId == rhsOptionPeer.optionId { + case let .optionPeer(rhsOptionId, _, _, _, _, _, _, _, _, _): + if lhsOptionId == rhsOptionId { return false } else { - return lhsOptionExpand.optionId < rhsOptionPeer.optionId + return lhsOptionId < rhsOptionId } - case let .optionExpand(rhsOptionExpand): - if lhsOptionExpand.optionId == rhsOptionExpand.optionId { + case let .optionExpand(rhsOptionId, _, _, _): + if lhsOptionId == rhsOptionId { return false } else { - return lhsOptionExpand.optionId < rhsOptionExpand.optionId + return lhsOptionId < rhsOptionId } } } @@ -391,8 +391,8 @@ public func pollResultsController(context: AccountContext, messageId: MessageId, var isFirstOption = true loop: for i in 0 ..< entries.count { switch entries[i] { - case let .optionPeer(optionPeer): - if optionPeer.opaqueIdentifier == focusOnOptionWithOpaqueIdentifier { + case let .optionPeer(_, _, _, _, _, _, _, opaqueIdentifier, _, _): + if opaqueIdentifier == focusOnOptionWithOpaqueIdentifier { if !isFirstOption { initialScrollToItem = ListViewScrollToItem(index: i, position: .top(0.0), animated: false, curve: .Default(duration: nil), directionHint: .Down) } diff --git a/submodules/TelegramUI/Sources/PrefetchManager.swift b/submodules/TelegramUI/Sources/PrefetchManager.swift index 08dcbcd4dd..f381a6a487 100644 --- a/submodules/TelegramUI/Sources/PrefetchManager.swift +++ b/submodules/TelegramUI/Sources/PrefetchManager.swift @@ -54,7 +54,7 @@ private final class PrefetchManagerInnerImpl { let appConfiguration = account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> take(1) |> map { view in - return view.values[PreferencesKeys.appConfiguration] as? AppConfiguration ?? .defaultValue + return view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) ?? .defaultValue } let orderedPreloadMedia = combineLatest(account.viewTracker.orderedPreloadMedia, TelegramEngine(account: account).stickers.loadedStickerPack(reference: .animatedEmoji, forceActualized: false), appConfiguration) diff --git a/submodules/TelegramUI/Sources/ShareExtensionContext.swift b/submodules/TelegramUI/Sources/ShareExtensionContext.swift index 559013266f..c27a0ad02e 100644 --- a/submodules/TelegramUI/Sources/ShareExtensionContext.swift +++ b/submodules/TelegramUI/Sources/ShareExtensionContext.swift @@ -248,7 +248,7 @@ public class ShareRootControllerImpl { } let account: Signal<(SharedAccountContextImpl, Account, [AccountWithInfo]), ShareAuthorizationError> = internalContext.sharedContext.accountManager.transaction { transaction -> (SharedAccountContextImpl, LoggingSettings) in - return (internalContext.sharedContext, transaction.getSharedData(SharedDataKeys.loggingSettings) as? LoggingSettings ?? LoggingSettings.defaultSettings) + return (internalContext.sharedContext, transaction.getSharedData(SharedDataKeys.loggingSettings)?.get(LoggingSettings.self) ?? LoggingSettings.defaultSettings) } |> castError(ShareAuthorizationError.self) |> mapToSignal { sharedContext, loggingSettings -> Signal<(SharedAccountContextImpl, Account, [AccountWithInfo]), ShareAuthorizationError> in @@ -261,7 +261,7 @@ public class ShareRootControllerImpl { let accountRecords = Set(transaction.getRecords().map { record in return record.id }) - let intentsSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.intentsSettings) as? IntentsSettings ?? IntentsSettings.defaultSettings + let intentsSettings = transaction.getSharedData(ApplicationSpecificSharedDataKeys.intentsSettings)?.get(IntentsSettings.self) ?? IntentsSettings.defaultSettings return (accountRecords, intentsSettings.account) }) |> castError(ShareAuthorizationError.self) @@ -300,7 +300,7 @@ public class ShareRootControllerImpl { |> mapToSignal { sharedContext, account, otherAccounts -> Signal<(AccountContext, PostboxAccessChallengeData, [AccountWithInfo]), ShareAuthorizationError> in let limitsConfigurationAndContentSettings = account.postbox.transaction { transaction -> (LimitsConfiguration, ContentSettings, AppConfiguration) in return ( - transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue, + transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue, getContentSettings(transaction: transaction), getAppConfiguration(transaction: transaction) ) diff --git a/submodules/TelegramUI/Sources/SharedAccountContext.swift b/submodules/TelegramUI/Sources/SharedAccountContext.swift index 46928694bf..940c314436 100644 --- a/submodules/TelegramUI/Sources/SharedAccountContext.swift +++ b/submodules/TelegramUI/Sources/SharedAccountContext.swift @@ -205,8 +205,8 @@ public final class SharedAccountContextImpl: SharedAccountContext { self._automaticMediaDownloadSettings.set(.single(initialPresentationDataAndSettings.automaticMediaDownloadSettings) |> then(accountManager.sharedData(keys: [SharedDataKeys.autodownloadSettings, ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]) |> map { sharedData in - let autodownloadSettings: AutodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings ?? .defaultSettings - let automaticDownloadSettings: MediaAutoDownloadSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings ?? .defaultSettings + let autodownloadSettings: AutodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) ?? .defaultSettings + let automaticDownloadSettings: MediaAutoDownloadSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) ?? .defaultSettings return automaticDownloadSettings.updatedWithAutodownloadSettings(autodownloadSettings) } )) @@ -253,7 +253,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { self._autodownloadSettings.set(.single(initialPresentationDataAndSettings.autodownloadSettings) |> then(accountManager.sharedData(keys: [SharedDataKeys.autodownloadSettings]) |> map { sharedData in - let autodownloadSettings: AutodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings] as? AutodownloadSettings ?? .defaultSettings + let autodownloadSettings: AutodownloadSettings = sharedData.entries[SharedDataKeys.autodownloadSettings]?.get(AutodownloadSettings.self) ?? .defaultSettings return autodownloadSettings } )) @@ -291,7 +291,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { self.inAppNotificationSettingsDisposable = (self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.inAppNotificationSettings]) |> deliverOnMainQueue).start(next: { [weak self] sharedData in if let strongSelf = self { - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) { let _ = strongSelf.currentInAppNotificationSettings.swap(settings) } } @@ -300,7 +300,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { self.mediaInputSettingsDisposable = (self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.mediaInputSettings]) |> deliverOnMainQueue).start(next: { [weak self] sharedData in if let strongSelf = self { - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.mediaInputSettings] as? MediaInputSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.mediaInputSettings]?.get(MediaInputSettings.self) { let _ = strongSelf.currentMediaInputSettings.swap(settings) } } @@ -310,7 +310,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { let _ = immediateExperimentalUISettingsValue.swap(initialPresentationDataAndSettings.experimentalUISettings) self.experimentalUISettingsDisposable = (self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.experimentalUISettings]) |> deliverOnMainQueue).start(next: { sharedData in - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings] as? ExperimentalUISettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.experimentalUISettings]?.get(ExperimentalUISettings.self) { let _ = immediateExperimentalUISettingsValue.swap(settings) } }) @@ -412,7 +412,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { return nil }) return account.postbox.transaction { transaction -> AddedAccountResult in - let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration) as? LimitsConfiguration ?? LimitsConfiguration.defaultValue + let limitsConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.limitsConfiguration)?.get(LimitsConfiguration.self) ?? LimitsConfiguration.defaultValue let contentSettings = getContentSettings(transaction: transaction) let appConfiguration = getAppConfiguration(transaction: transaction) return .ready(id, account, attributes.sortIndex, limitsConfiguration, contentSettings, appConfiguration) @@ -769,7 +769,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { let enableSpotlight = accountManager.sharedData(keys: Set([ApplicationSpecificSharedDataKeys.intentsSettings])) |> map { sharedData -> Bool in - let intentsSettings: IntentsSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings] as? IntentsSettings ?? .defaultSettings + let intentsSettings: IntentsSettings = sharedData.entries[ApplicationSpecificSharedDataKeys.intentsSettings]?.get(IntentsSettings.self) ?? .defaultSettings return intentsSettings.contacts } |> distinctUntilChanged @@ -837,7 +837,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { let settings = self.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.inAppNotificationSettings]) |> map { sharedData -> (allAccounts: Bool, includeMuted: Bool) in - let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings] as? InAppNotificationSettings ?? InAppNotificationSettings.defaultSettings + let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.inAppNotificationSettings]?.get(InAppNotificationSettings.self) ?? InAppNotificationSettings.defaultSettings return (settings.displayNotificationsFromAllAccounts, false) } |> distinctUntilChanged(isEqual: { lhs, rhs in diff --git a/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift b/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift index 0023d3a103..9b0a70435a 100644 --- a/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift +++ b/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift @@ -156,7 +156,7 @@ private final class DownloadedMediaStoreManagerPrivateImpl { self.appSpecificAssetCollectionValue = Promise(initializeOnFirstAccess: appSpecificAssetCollection()) self.storeSettings.set(accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]) |> map { sharedData -> MediaAutoDownloadSettings in - if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings { + if let settings = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]?.get(MediaAutoDownloadSettings.self) { return settings } else { return .defaultSettings diff --git a/submodules/TelegramUI/Sources/ThemeUpdateManager.swift b/submodules/TelegramUI/Sources/ThemeUpdateManager.swift index cc9014cef7..28752c2da3 100644 --- a/submodules/TelegramUI/Sources/ThemeUpdateManager.swift +++ b/submodules/TelegramUI/Sources/ThemeUpdateManager.swift @@ -40,7 +40,7 @@ final class ThemeUpdateManagerImpl: ThemeUpdateManager { self.disposable = (sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.presentationThemeSettings]) |> map { sharedData -> PresentationThemeSettings in - return (sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings] as? PresentationThemeSettings) ?? PresentationThemeSettings.defaultSettings + return sharedData.entries[ApplicationSpecificSharedDataKeys.presentationThemeSettings]?.get(PresentationThemeSettings.self) ?? PresentationThemeSettings.defaultSettings } |> deliverOn(queue)).start(next: { [weak self] themeSettings in self?.presentationThemeSettingsUpdated(themeSettings) @@ -124,7 +124,7 @@ final class ThemeUpdateManagerImpl: ThemeUpdateManager { let _ = (accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings, { entry in let current: PresentationThemeSettings - if let entry = entry as? PresentationThemeSettings { + if let entry = entry?.get(PresentationThemeSettings.self) { current = entry } else { current = PresentationThemeSettings.defaultSettings @@ -138,7 +138,7 @@ final class ThemeUpdateManagerImpl: ThemeUpdateManager { theme = updatedTheme } - return PresentationThemeSettings(theme: theme, themeSpecificAccentColors: current.themeSpecificAccentColors, themeSpecificChatWallpapers: current.themeSpecificChatWallpapers, useSystemFont: current.useSystemFont, fontSize: current.fontSize, listsFontSize: current.listsFontSize, chatBubbleSettings: current.chatBubbleSettings, automaticThemeSwitchSetting: automaticThemeSwitchSetting, largeEmoji: current.largeEmoji, reduceMotion: current.reduceMotion) + return PreferencesEntry(PresentationThemeSettings(theme: theme, themeSpecificAccentColors: current.themeSpecificAccentColors, themeSpecificChatWallpapers: current.themeSpecificChatWallpapers, useSystemFont: current.useSystemFont, fontSize: current.fontSize, listsFontSize: current.listsFontSize, chatBubbleSettings: current.chatBubbleSettings, automaticThemeSwitchSetting: automaticThemeSwitchSetting, largeEmoji: current.largeEmoji, reduceMotion: current.reduceMotion)) }) }).start() } diff --git a/submodules/TelegramUI/Sources/UpgradedAccounts.swift b/submodules/TelegramUI/Sources/UpgradedAccounts.swift index a02625e868..8423358e4f 100644 --- a/submodules/TelegramUI/Sources/UpgradedAccounts.swift +++ b/submodules/TelegramUI/Sources/UpgradedAccounts.swift @@ -103,11 +103,7 @@ private let applicationSpecificPreferencesKeyMapping: [LegacyApplicationSpecific ] private func upgradedSharedDataValue(_ value: PreferencesEntry?) -> PreferencesEntry? { - if let settings = value as? AutomaticMediaDownloadSettings { - return MediaAutoDownloadSettings.upgradeLegacySettings(settings) - } else { - return value - } + return value } public func upgradedAccounts(accountManager: AccountManager, rootPath: String, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { @@ -154,7 +150,7 @@ public func upgradedAccounts(accountManager: AccountManager (ContactSynchronizationSettings, [AccountRecordId]) in - return (transaction.getSharedData(ApplicationSpecificSharedDataKeys.contactSynchronizationSettings) as? ContactSynchronizationSettings ?? ContactSynchronizationSettings.defaultSettings, transaction.getRecords().map({ $0.id })) + return (transaction.getSharedData(ApplicationSpecificSharedDataKeys.contactSynchronizationSettings)?.get(ContactSynchronizationSettings.self) ?? ContactSynchronizationSettings.defaultSettings, transaction.getRecords().map({ $0.id })) } |> mapToSignal { globalSettings, ids -> Signal in var importSignal: Signal = .complete() for id in ids { let importInfoAccounttSignal = accountTransaction(rootPath: rootPath, id: id, encryptionParameters: encryptionParameters, isReadOnly: false, transaction: { _, transaction -> Void in transaction.updatePreferencesEntry(key: PreferencesKeys.contactsSettings, { current in - var settings = current as? ContactsSettings ?? ContactsSettings.defaultSettings + var settings = current?.get(ContactsSettings.self) ?? ContactsSettings.defaultSettings settings.synchronizeContacts = globalSettings._legacySynchronizeDeviceContacts - return settings + return PreferencesEntry(settings) }) }) |> ignoreValues @@ -310,7 +306,6 @@ public func upgradedAccounts(accountManager: AccountManager then( applyVersion )) |> mapToSignal { _ -> Signal in - return .complete() } ) } diff --git a/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputContextPanelNode.swift b/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputContextPanelNode.swift index fd8185623d..e3a3c8d718 100644 --- a/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputContextPanelNode.swift +++ b/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputContextPanelNode.swift @@ -14,12 +14,12 @@ private enum VerticalChatContextResultsEntryStableId: Hashable { case action case result(ChatContextResult) - var hashValue: Int { + func hash(into hasher: inout Hasher) { switch self { case .action: - return 0 + hasher.combine(0) case let .result(result): - return result.id.hashValue + hasher.combine(result.id.hashValue) } } diff --git a/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputPanelItem.swift b/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputPanelItem.swift index cbbfda0c29..7cc0ce5527 100644 --- a/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputPanelItem.swift +++ b/submodules/TelegramUI/Sources/VerticalListContextResultsChatInputPanelItem.swift @@ -196,7 +196,7 @@ final class VerticalListContextResultsChatInputPanelItemNode: ListViewItemNode { } if let selectedUrl = selectedUrl, let parsedUrl = URL(string: selectedUrl) { if let host = parsedUrl.host, !host.isEmpty { - iconText = NSAttributedString(string: host.substring(to: host.index(after: host.startIndex)).uppercased(), font: iconFont, textColor: UIColor.white) + iconText = NSAttributedString(string: String(host[.. Bool { - if let to = to as? ExperimentalUISettings { - return self == to - } else { - return false - } + try container.encode((self.keepChatNavigationStack ? 1 : 0) as Int32, forKey: "keepChatNavigationStack") + try container.encode((self.skipReadHistory ? 1 : 0) as Int32, forKey: "skipReadHistory") + try container.encode((self.crashOnLongQueries ? 1 : 0) as Int32, forKey: "crashOnLongQueries") + try container.encode((self.chatListPhotos ? 1 : 0) as Int32, forKey: "chatListPhotos") + try container.encode((self.knockoutWallpaper ? 1 : 0) as Int32, forKey: "knockoutWallpaper") + try container.encode((self.foldersTabAtBottom ? 1 : 0) as Int32, forKey: "foldersTabAtBottom") + try container.encode((self.playerEmbedding ? 1 : 0) as Int32, forKey: "playerEmbedding") + try container.encode((self.playlistPlayback ? 1 : 0) as Int32, forKey: "playlistPlayback") + try container.encodeIfPresent(self.preferredVideoCodec, forKey: "preferredVideoCodec") + try container.encode((self.disableVideoAspectScaling ? 1 : 0) as Int32, forKey: "disableVideoAspectScaling") + try container.encode((self.enableVoipTcp ? 1 : 0) as Int32, forKey: "enableVoipTcp") + try container.encode((self.experimentalCompatibility ? 1 : 0) as Int32, forKey: "experimentalCompatibility") + try container.encode((self.enableDebugDataDisplay ? 1 : 0) as Int32, forKey: "enableDebugDataDisplay") } } @@ -122,12 +107,12 @@ public func updateExperimentalUISettingsInteractively(accountManager: AccountMan return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { entry in let currentSettings: ExperimentalUISettings - if let entry = entry as? ExperimentalUISettings { + if let entry = entry?.get(ExperimentalUISettings.self) { currentSettings = entry } else { currentSettings = .defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift b/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift index c8473ee338..5a895ba369 100644 --- a/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct GeneratedMediaStoreSettings: PreferencesEntry, Equatable { +public struct GeneratedMediaStoreSettings: Codable, Equatable { public let storeEditedPhotos: Bool public let storeCapturedMedia: Bool @@ -16,22 +16,18 @@ public struct GeneratedMediaStoreSettings: PreferencesEntry, Equatable { self.storeCapturedMedia = storeCapturedMedia } - public init(decoder: PostboxDecoder) { - self.storeEditedPhotos = decoder.decodeInt32ForKey("eph", orElse: 0) != 0 - self.storeCapturedMedia = decoder.decodeInt32ForKey("cpm", orElse: 0) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.storeEditedPhotos = (try container.decode(Int32.self, forKey: "eph")) != 0 + self.storeCapturedMedia = (try container.decode(Int32.self, forKey: "cpm")) != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.storeEditedPhotos ? 1 : 0, forKey: "eph") - encoder.encodeInt32(self.storeCapturedMedia ? 1 : 0, forKey: "cpm") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? GeneratedMediaStoreSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.storeEditedPhotos ? 1 : 0) as Int32, forKey: "eph") + try container.encode((self.storeCapturedMedia ? 1 : 0) as Int32, forKey: "cpm") } public static func ==(lhs: GeneratedMediaStoreSettings, rhs: GeneratedMediaStoreSettings) -> Bool { @@ -47,12 +43,12 @@ public func updateGeneratedMediaStoreSettingsInteractively(accountManager: Accou return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings, { entry in let currentSettings: GeneratedMediaStoreSettings - if let entry = entry as? GeneratedMediaStoreSettings { + if let entry = entry?.get(GeneratedMediaStoreSettings.self) { currentSettings = entry } else { currentSettings = GeneratedMediaStoreSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift b/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift index 458f92472e..aca5725d3b 100644 --- a/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift @@ -28,7 +28,7 @@ public enum TotalUnreadCountDisplayCategory: Int32 { } } -public struct InAppNotificationSettings: PreferencesEntry, Equatable { +public struct InAppNotificationSettings: Codable, Equatable { public var playSounds: Bool public var vibrate: Bool public var displayPreviews: Bool @@ -53,15 +53,17 @@ public struct InAppNotificationSettings: PreferencesEntry, Equatable { self.displayNotificationsFromAllAccounts = displayNotificationsFromAllAccounts } - public init(decoder: PostboxDecoder) { - self.playSounds = decoder.decodeInt32ForKey("s", orElse: 0) != 0 - self.vibrate = decoder.decodeInt32ForKey("v", orElse: 0) != 0 - self.displayPreviews = decoder.decodeInt32ForKey("p", orElse: 0) != 0 - self.totalUnreadCountDisplayStyle = TotalUnreadCountDisplayStyle(rawValue: decoder.decodeInt32ForKey("cds", orElse: 0)) ?? .filtered - self.totalUnreadCountDisplayCategory = TotalUnreadCountDisplayCategory(rawValue: decoder.decodeInt32ForKey("totalUnreadCountDisplayCategory", orElse: 1)) ?? .messages - if let value = decoder.decodeOptionalInt32ForKey("totalUnreadCountIncludeTags_2") { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.playSounds = (try container.decode(Int32.self, forKey: "s")) != 0 + self.vibrate = (try container.decode(Int32.self, forKey: "v")) != 0 + self.displayPreviews = (try container.decode(Int32.self, forKey: "p")) != 0 + self.totalUnreadCountDisplayStyle = TotalUnreadCountDisplayStyle(rawValue: try container.decode(Int32.self, forKey: "cds")) ?? .filtered + self.totalUnreadCountDisplayCategory = TotalUnreadCountDisplayCategory(rawValue: try container.decodeIfPresent(Int32.self, forKey: "totalUnreadCountDisplayCategory") ?? 1) ?? .messages + if let value = try container.decodeIfPresent(Int32.self, forKey: "totalUnreadCountIncludeTags_2") { self.totalUnreadCountIncludeTags = PeerSummaryCounterTags(rawValue: value) - } else if let value = decoder.decodeOptionalInt32ForKey("totalUnreadCountIncludeTags") { + } else if let value = try container.decodeIfPresent(Int32.self, forKey: "totalUnreadCountIncludeTags") { var resultTags: PeerSummaryCounterTags = [] for legacyTag in LegacyPeerSummaryCounterTags(rawValue: value) { if legacyTag == .regularChatsAndPrivateGroups { @@ -79,27 +81,21 @@ public struct InAppNotificationSettings: PreferencesEntry, Equatable { } else { self.totalUnreadCountIncludeTags = .all } - self.displayNameOnLockscreen = decoder.decodeInt32ForKey("displayNameOnLockscreen", orElse: 1) != 0 - self.displayNotificationsFromAllAccounts = decoder.decodeInt32ForKey("displayNotificationsFromAllAccounts", orElse: 1) != 0 + self.displayNameOnLockscreen = (try container.decodeIfPresent(Int32.self, forKey: "displayNameOnLockscreen") ?? 1) != 0 + self.displayNotificationsFromAllAccounts = (try container.decodeIfPresent(Int32.self, forKey: "displayNotificationsFromAllAccounts") ?? 1) != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.playSounds ? 1 : 0, forKey: "s") - encoder.encodeInt32(self.vibrate ? 1 : 0, forKey: "v") - encoder.encodeInt32(self.displayPreviews ? 1 : 0, forKey: "p") - encoder.encodeInt32(self.totalUnreadCountDisplayStyle.rawValue, forKey: "cds") - encoder.encodeInt32(self.totalUnreadCountDisplayCategory.rawValue, forKey: "totalUnreadCountDisplayCategory") - encoder.encodeInt32(self.totalUnreadCountIncludeTags.rawValue, forKey: "totalUnreadCountIncludeTags_2") - encoder.encodeInt32(self.displayNameOnLockscreen ? 1 : 0, forKey: "displayNameOnLockscreen") - encoder.encodeInt32(self.displayNotificationsFromAllAccounts ? 1 : 0, forKey: "displayNotificationsFromAllAccounts") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? InAppNotificationSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.playSounds ? 1 : 0) as Int32, forKey: "s") + try container.encode((self.vibrate ? 1 : 0) as Int32, forKey: "v") + try container.encode((self.displayPreviews ? 1 : 0) as Int32, forKey: "p") + try container.encode(self.totalUnreadCountDisplayStyle.rawValue, forKey: "cds") + try container.encode(self.totalUnreadCountDisplayCategory.rawValue, forKey: "totalUnreadCountDisplayCategory") + try container.encode(self.totalUnreadCountIncludeTags.rawValue, forKey: "totalUnreadCountIncludeTags_2") + try container.encode((self.displayNameOnLockscreen ? 1 : 0) as Int32, forKey: "displayNameOnLockscreen") + try container.encode((self.displayNotificationsFromAllAccounts ? 1 : 0) as Int32, forKey: "displayNotificationsFromAllAccounts") } } @@ -107,12 +103,12 @@ public func updateInAppNotificationSettingsInteractively(accountManager: Account return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings, { entry in let currentSettings: InAppNotificationSettings - if let entry = entry as? InAppNotificationSettings { + if let entry = entry?.get(InAppNotificationSettings.self) { currentSettings = entry } else { currentSettings = InAppNotificationSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift b/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift index 24196f6a02..26a1ddba44 100644 --- a/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift @@ -18,7 +18,7 @@ public enum InstantPagePresentationFontSize: Int32 { case xxlarge = 4 } -public final class InstantPagePresentationSettings: PreferencesEntry, Equatable { +public final class InstantPagePresentationSettings: Codable, Equatable { public static var defaultSettings = InstantPagePresentationSettings(themeType: .light, fontSize: .standard, forceSerif: false, autoNightMode: true, ignoreAutoNightModeUntil: 0) public var themeType: InstantPageThemeType @@ -35,28 +35,24 @@ public final class InstantPagePresentationSettings: PreferencesEntry, Equatable self.ignoreAutoNightModeUntil = ignoreAutoNightModeUntil } - public init(decoder: PostboxDecoder) { - self.themeType = InstantPageThemeType(rawValue: decoder.decodeInt32ForKey("themeType", orElse: 0))! - self.fontSize = InstantPagePresentationFontSize(rawValue: decoder.decodeInt32ForKey("fontSize", orElse: 0))! - self.forceSerif = decoder.decodeInt32ForKey("forceSerif", orElse: 0) != 0 - self.autoNightMode = decoder.decodeInt32ForKey("autoNightMode", orElse: 0) != 0 - self.ignoreAutoNightModeUntil = decoder.decodeInt32ForKey("ignoreAutoNightModeUntil", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.themeType = InstantPageThemeType(rawValue: try container.decode(Int32.self, forKey: "themeType"))! + self.fontSize = InstantPagePresentationFontSize(rawValue: try container.decode(Int32.self, forKey: "fontSize"))! + self.forceSerif = try container.decode(Int32.self, forKey: "forceSerif") != 0 + self.autoNightMode = try container.decode(Int32.self, forKey: "autoNightMode") != 0 + self.ignoreAutoNightModeUntil = try container.decode(Int32.self, forKey: "ignoreAutoNightModeUntil") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.themeType.rawValue, forKey: "themeType") - encoder.encodeInt32(self.fontSize.rawValue, forKey: "fontSize") - encoder.encodeInt32(self.forceSerif ? 1 : 0, forKey: "forceSerif") - encoder.encodeInt32(self.autoNightMode ? 1 : 0, forKey: "autoNightMode") - encoder.encodeInt32(self.ignoreAutoNightModeUntil, forKey: "ignoreAutoNightModeUntil") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? InstantPagePresentationSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.themeType.rawValue, forKey: "themeType") + try container.encode(self.fontSize.rawValue, forKey: "fontSize") + try container.encode((self.forceSerif ? 1 : 0) as Int32, forKey: "forceSerif") + try container.encode((self.autoNightMode ? 1 : 0) as Int32, forKey: "autoNightMode") + try container.encode(self.ignoreAutoNightModeUntil, forKey: "ignoreAutoNightModeUntil") } public static func ==(lhs: InstantPagePresentationSettings, rhs: InstantPagePresentationSettings) -> Bool { @@ -103,12 +99,12 @@ public func updateInstantPagePresentationSettingsInteractively(accountManager: A return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.instantPagePresentationSettings, { entry in let currentSettings: InstantPagePresentationSettings - if let entry = entry as? InstantPagePresentationSettings { + if let entry = entry?.get(InstantPagePresentationSettings.self) { currentSettings = entry } else { currentSettings = InstantPagePresentationSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift b/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift index 221f946fe0..19e0c85704 100644 --- a/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct IntentsSettings: PreferencesEntry, Equatable { +public struct IntentsSettings: Codable, Equatable { public let initiallyReset: Bool public let account: PeerId? @@ -27,36 +27,28 @@ public struct IntentsSettings: PreferencesEntry, Equatable { self.onlyShared = onlyShared } - public init(decoder: PostboxDecoder) { - self.initiallyReset = decoder.decodeBoolForKey("initiallyReset_v2", orElse: false) - self.account = decoder.decodeOptionalInt64ForKey("account").flatMap { PeerId($0) } - self.contacts = decoder.decodeBoolForKey("contacts", orElse: true) - self.privateChats = decoder.decodeBoolForKey("privateChats", orElse: false) - self.savedMessages = decoder.decodeBoolForKey("savedMessages", orElse: true) - self.groups = decoder.decodeBoolForKey("groups", orElse: false) - self.onlyShared = decoder.decodeBoolForKey("onlyShared", orElse: false) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.initiallyReset = try container.decodeIfPresent(Bool.self, forKey: "initiallyReset_v2") ?? false + self.account = (try container.decodeIfPresent(Int64.self, forKey: "account")).flatMap { PeerId($0) } + self.contacts = try container.decodeIfPresent(Bool.self, forKey: "contacts") ?? true + self.privateChats = try container.decodeIfPresent(Bool.self, forKey: "privateChats") ?? false + self.savedMessages = try container.decodeIfPresent(Bool.self, forKey: "savedMessages") ?? true + self.groups = try container.decodeIfPresent(Bool.self, forKey: "groups") ?? false + self.onlyShared = try container.decodeIfPresent(Bool.self, forKey: "onlyShared") ?? false } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeBool(self.initiallyReset, forKey: "initiallyReset_v2") - if let account = self.account { - encoder.encodeInt64(account.toInt64(), forKey: "account") - } else { - encoder.encodeNil(forKey: "account") - } - encoder.encodeBool(self.contacts, forKey: "contacts") - encoder.encodeBool(self.privateChats, forKey: "privateChats") - encoder.encodeBool(self.savedMessages, forKey: "savedMessages") - encoder.encodeBool(self.groups, forKey: "groups") - encoder.encodeBool(self.onlyShared, forKey: "onlyShared") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? IntentsSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.initiallyReset, forKey: "initiallyReset_v2") + try container.encodeIfPresent(self.account?.toInt64(), forKey: "account") + try container.encode(self.contacts, forKey: "contacts") + try container.encode(self.privateChats, forKey: "privateChats") + try container.encode(self.savedMessages, forKey: "savedMessages") + try container.encode(self.groups, forKey: "groups") + try container.encode(self.onlyShared, forKey: "onlyShared") } public static func ==(lhs: IntentsSettings, rhs: IntentsSettings) -> Bool { @@ -95,14 +87,14 @@ public func updateIntentsSettingsInteractively(accountManager: AccountManager Bool { - if let to = to as? AutomaticMediaDownloadSettings { - return self == to - } else { - return false - } - } -} diff --git a/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift b/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift index c6a262d0a7..75f9a8e7f5 100644 --- a/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift @@ -27,7 +27,7 @@ public enum MediaAutoDownloadPreset: Int32 { case custom } -public struct MediaAutoDownloadPresets: PostboxCoding, Equatable { +public struct MediaAutoDownloadPresets: Codable, Equatable { public var low: MediaAutoDownloadCategories public var medium: MediaAutoDownloadCategories public var high: MediaAutoDownloadCategories @@ -38,20 +38,24 @@ public struct MediaAutoDownloadPresets: PostboxCoding, Equatable { self.high = high } - public init(decoder: PostboxDecoder) { - self.low = decoder.decodeObjectForKey("low", decoder: MediaAutoDownloadCategories.init(decoder:)) as! MediaAutoDownloadCategories - self.medium = decoder.decodeObjectForKey("medium", decoder: MediaAutoDownloadCategories.init(decoder:)) as! MediaAutoDownloadCategories - self.high = decoder.decodeObjectForKey("high", decoder: MediaAutoDownloadCategories.init(decoder:)) as! MediaAutoDownloadCategories + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.low = try container.decode(MediaAutoDownloadCategories.self, forKey: "low") + self.medium = try container.decode(MediaAutoDownloadCategories.self, forKey: "medium") + self.high = try container.decode(MediaAutoDownloadCategories.self, forKey: "high") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.low, forKey: "low") - encoder.encodeObject(self.medium, forKey: "medium") - encoder.encodeObject(self.high, forKey: "high") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.low, forKey: "low") + try container.encode(self.medium, forKey: "medium") + try container.encode(self.high, forKey: "high") } } -public struct MediaAutoDownloadConnection: PostboxCoding, Equatable { +public struct MediaAutoDownloadConnection: Codable, Equatable { public var enabled: Bool public var preset: MediaAutoDownloadPreset public var custom: MediaAutoDownloadCategories? @@ -62,24 +66,24 @@ public struct MediaAutoDownloadConnection: PostboxCoding, Equatable { self.custom = custom } - public init(decoder: PostboxDecoder) { - self.enabled = decoder.decodeInt32ForKey("enabled", orElse: 0) != 0 - self.preset = MediaAutoDownloadPreset(rawValue: decoder.decodeInt32ForKey("preset", orElse: 0)) ?? .medium - self.custom = decoder.decodeObjectForKey("custom", decoder: MediaAutoDownloadCategories.init(decoder:)) as? MediaAutoDownloadCategories + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.enabled = try container.decode(Int32.self, forKey: "enabled") != 0 + self.preset = MediaAutoDownloadPreset(rawValue: try container.decode(Int32.self, forKey: "preset")) ?? .medium + self.custom = try container.decodeIfPresent(MediaAutoDownloadCategories.self, forKey: "custom") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.enabled ? 1 : 0, forKey: "enabled") - encoder.encodeInt32(self.preset.rawValue, forKey: "preset") - if let custom = self.custom { - encoder.encodeObject(custom, forKey: "custom") - } else { - encoder.encodeNil(forKey: "custom") - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.enabled ? 1 : 0) as Int32, forKey: "enabled") + try container.encode(self.preset.rawValue, forKey: "preset") + try container.encodeIfPresent(self.custom, forKey: "custom") } } -public struct MediaAutoDownloadCategories: PostboxCoding, Equatable, Comparable { +public struct MediaAutoDownloadCategories: Codable, Equatable, Comparable { public var basePreset: MediaAutoDownloadPreset public var photo: MediaAutoDownloadCategory public var video: MediaAutoDownloadCategory @@ -92,18 +96,22 @@ public struct MediaAutoDownloadCategories: PostboxCoding, Equatable, Comparable self.file = file } - public init(decoder: PostboxDecoder) { - self.basePreset = MediaAutoDownloadPreset(rawValue: decoder.decodeInt32ForKey("preset", orElse: 0)) ?? .medium - self.photo = decoder.decodeObjectForKey("photo", decoder: MediaAutoDownloadCategory.init(decoder:)) as! MediaAutoDownloadCategory - self.video = decoder.decodeObjectForKey("video", decoder: MediaAutoDownloadCategory.init(decoder:)) as! MediaAutoDownloadCategory - self.file = decoder.decodeObjectForKey("file", decoder: MediaAutoDownloadCategory.init(decoder:)) as! MediaAutoDownloadCategory + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.basePreset = MediaAutoDownloadPreset(rawValue: try container.decode(Int32.self, forKey: "preset")) ?? .medium + self.photo = try container.decode(MediaAutoDownloadCategory.self, forKey: "photo") + self.video = try container.decode(MediaAutoDownloadCategory.self, forKey: "video") + self.file = try container.decode(MediaAutoDownloadCategory.self, forKey: "file") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.basePreset.rawValue, forKey: "preset") - encoder.encodeObject(self.photo, forKey: "photo") - encoder.encodeObject(self.video, forKey: "video") - encoder.encodeObject(self.file, forKey: "file") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.basePreset.rawValue, forKey: "preset") + try container.encode(self.photo, forKey: "photo") + try container.encode(self.video, forKey: "video") + try container.encode(self.file, forKey: "file") } public static func < (lhs: MediaAutoDownloadCategories, rhs: MediaAutoDownloadCategories) -> Bool { @@ -113,7 +121,7 @@ public struct MediaAutoDownloadCategories: PostboxCoding, Equatable, Comparable } } -public struct MediaAutoDownloadCategory: PostboxCoding, Equatable { +public struct MediaAutoDownloadCategory: Codable, Equatable { public var contacts: Bool public var otherPrivate: Bool public var groups: Bool @@ -130,26 +138,30 @@ public struct MediaAutoDownloadCategory: PostboxCoding, Equatable { self.predownload = predownload } - public init(decoder: PostboxDecoder) { - self.contacts = decoder.decodeInt32ForKey("contacts", orElse: 0) != 0 - self.otherPrivate = decoder.decodeInt32ForKey("otherPrivate", orElse: 0) != 0 - self.groups = decoder.decodeInt32ForKey("groups", orElse: 0) != 0 - self.channels = decoder.decodeInt32ForKey("channels", orElse: 0) != 0 - self.sizeLimit = decoder.decodeInt32ForKey("size", orElse: 0) - self.predownload = decoder.decodeInt32ForKey("predownload", orElse: 0) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.contacts = try container.decode(Int32.self, forKey: "contacts") != 0 + self.otherPrivate = try container.decode(Int32.self, forKey: "otherPrivate") != 0 + self.groups = try container.decode(Int32.self, forKey: "groups") != 0 + self.channels = try container.decode(Int32.self, forKey: "channels") != 0 + self.sizeLimit = try container.decode(Int32.self, forKey: "size") + self.predownload = try container.decode(Int32.self, forKey: "predownload") != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.contacts ? 1 : 0, forKey: "contacts") - encoder.encodeInt32(self.otherPrivate ? 1 : 0, forKey: "otherPrivate") - encoder.encodeInt32(self.groups ? 1 : 0, forKey: "groups") - encoder.encodeInt32(self.channels ? 1 : 0, forKey: "channels") - encoder.encodeInt32(self.sizeLimit, forKey: "size") - encoder.encodeInt32(self.predownload ? 1 : 0, forKey: "predownload") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.contacts ? 1 : 0) as Int32, forKey: "contacts") + try container.encode((self.otherPrivate ? 1 : 0) as Int32, forKey: "otherPrivate") + try container.encode((self.groups ? 1 : 0) as Int32, forKey: "groups") + try container.encode((self.channels ? 1 : 0) as Int32, forKey: "channels") + try container.encode(self.sizeLimit, forKey: "size") + try container.encode((self.predownload ? 1 : 0) as Int32, forKey: "predownload") } } -public struct MediaAutoDownloadSettings: PreferencesEntry, Equatable { +public struct MediaAutoDownloadSettings: Codable, Equatable { public var presets: MediaAutoDownloadPresets public var cellular: MediaAutoDownloadConnection public var wifi: MediaAutoDownloadConnection @@ -185,47 +197,32 @@ public struct MediaAutoDownloadSettings: PreferencesEntry, Equatable { self.downloadInBackground = downloadInBackground } - public static func upgradeLegacySettings(_ settings: AutomaticMediaDownloadSettings) -> MediaAutoDownloadSettings { - if settings == AutomaticMediaDownloadSettings.defaultSettings { - return MediaAutoDownloadSettings.defaultSettings - } - - let defaultSettings = MediaAutoDownloadSettings.defaultSettings - let saveDownloadedPhotos = MediaAutoDownloadCategory(contacts: settings.peers.contacts.saveDownloadedPhotos, otherPrivate: settings.peers.otherPrivate.saveDownloadedPhotos, groups: settings.peers.groups.saveDownloadedPhotos, channels: settings.peers.channels.saveDownloadedPhotos, sizeLimit: 0, predownload: false) - - let cellular = MediaAutoDownloadConnection(enabled: settings.masterEnabled, preset: .medium, custom: nil) - let wifi = MediaAutoDownloadConnection(enabled: settings.masterEnabled, preset: .high, custom: nil) - - return MediaAutoDownloadSettings(presets: defaultSettings.presets, cellular: cellular, wifi: wifi, saveDownloadedPhotos: saveDownloadedPhotos, autoplayGifs: settings.autoplayGifs, autoplayVideos: true, downloadInBackground: settings.downloadInBackground) - } - - public init(decoder: PostboxDecoder) { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + let defaultSettings = MediaAutoDownloadSettings.defaultSettings self.presets = defaultSettings.presets - self.cellular = decoder.decodeObjectForKey("cellular", decoder: MediaAutoDownloadConnection.init(decoder:)) as? MediaAutoDownloadConnection ?? defaultSettings.cellular - self.wifi = decoder.decodeObjectForKey("wifi", decoder: MediaAutoDownloadConnection.init(decoder:)) as? MediaAutoDownloadConnection ?? defaultSettings.wifi - self.saveDownloadedPhotos = decoder.decodeObjectForKey("saveDownloadedPhotos", decoder: MediaAutoDownloadCategory.init(decoder:)) as? MediaAutoDownloadCategory ?? defaultSettings.saveDownloadedPhotos - self.autoplayGifs = decoder.decodeInt32ForKey("autoplayGifs", orElse: 1) != 0 - self.autoplayVideos = decoder.decodeInt32ForKey("autoplayVideos", orElse: 1) != 0 - self.downloadInBackground = decoder.decodeInt32ForKey("downloadInBackground", orElse: 1) != 0 + + self.cellular = (try? container.decodeIfPresent(MediaAutoDownloadConnection.self, forKey: "cellular")) ?? defaultSettings.cellular + self.wifi = (try? container.decodeIfPresent(MediaAutoDownloadConnection.self, forKey: "wifi")) ?? defaultSettings.wifi + + self.saveDownloadedPhotos = (try? container.decodeIfPresent(MediaAutoDownloadCategory.self, forKey: "saveDownloadedPhotos")) ?? defaultSettings.saveDownloadedPhotos + + self.autoplayGifs = try container.decode(Int32.self, forKey: "autoplayGifs") != 0 + self.autoplayVideos = try container.decode(Int32.self, forKey: "autoplayVideos") != 0 + self.downloadInBackground = try container.decode(Int32.self, forKey: "downloadInBackground") != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.cellular, forKey: "cellular") - encoder.encodeObject(self.wifi, forKey: "wifi") - encoder.encodeObject(self.saveDownloadedPhotos, forKey: "saveDownloadedPhotos") - encoder.encodeInt32(self.autoplayGifs ? 1 : 0, forKey: "autoplayGifs") - encoder.encodeInt32(self.autoplayVideos ? 1 : 0, forKey: "autoplayVideos") - encoder.encodeInt32(self.downloadInBackground ? 1 : 0, forKey: "downloadInBackground") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? MediaAutoDownloadSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.cellular, forKey: "cellular") + try container.encode(self.wifi, forKey: "wifi") + try container.encode(self.saveDownloadedPhotos, forKey: "saveDownloadedPhotos") + try container.encode((self.autoplayGifs ? 1 : 0) as Int32, forKey: "autoplayGifs") + try container.encode((self.autoplayVideos ? 1 : 0) as Int32, forKey: "autoplayVideos") + try container.encode((self.downloadInBackground ? 1 : 0) as Int32, forKey: "downloadInBackground") } public func connectionSettings(for networkType: MediaAutoDownloadNetworkType) -> MediaAutoDownloadConnection { @@ -261,13 +258,13 @@ public func updateMediaDownloadSettingsInteractively(accountManager: AccountMana return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings, { entry in let currentSettings: MediaAutoDownloadSettings - if let entry = entry as? MediaAutoDownloadSettings { + if let entry = entry?.get(MediaAutoDownloadSettings.self) { currentSettings = entry } else { currentSettings = MediaAutoDownloadSettings.defaultSettings } let updated = f(currentSettings) - return updated + return PreferencesEntry(updated) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift b/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift index e1c5f49d42..df05ae0771 100644 --- a/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct MediaInputSettings: PreferencesEntry, Equatable { +public struct MediaInputSettings: Codable, Equatable { public let enableRaiseToSpeak: Bool public static var defaultSettings: MediaInputSettings { @@ -14,20 +14,16 @@ public struct MediaInputSettings: PreferencesEntry, Equatable { self.enableRaiseToSpeak = enableRaiseToSpeak } - public init(decoder: PostboxDecoder) { - self.enableRaiseToSpeak = decoder.decodeInt32ForKey("enableRaiseToSpeak", orElse: 1) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.enableRaiseToSpeak = (try container.decode(Int32.self, forKey: "enableRaiseToSpeak")) != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.enableRaiseToSpeak ? 1 : 0, forKey: "enableRaiseToSpeak") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? MediaInputSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.enableRaiseToSpeak ? 1 : 0) as Int32, forKey: "enableRaiseToSpeak") } public static func ==(lhs: MediaInputSettings, rhs: MediaInputSettings) -> Bool { @@ -43,12 +39,12 @@ public func updateMediaInputSettingsInteractively(accountManager: AccountManager return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.mediaInputSettings, { entry in let currentSettings: MediaInputSettings - if let entry = entry as? MediaInputSettings { + if let entry = entry?.get(MediaInputSettings.self) { currentSettings = entry } else { currentSettings = MediaInputSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift b/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift index 37d28f873f..f094a19775 100644 --- a/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift @@ -37,7 +37,7 @@ public enum AudioPlaybackRate: Int32 { } } -public struct MusicPlaybackSettings: PreferencesEntry, Equatable { +public struct MusicPlaybackSettings: Codable, Equatable { public var order: MusicPlaybackSettingsOrder public var looping: MusicPlaybackSettingsLooping public var voicePlaybackRate: AudioPlaybackRate @@ -52,24 +52,20 @@ public struct MusicPlaybackSettings: PreferencesEntry, Equatable { self.voicePlaybackRate = voicePlaybackRate } - public init(decoder: PostboxDecoder) { - self.order = MusicPlaybackSettingsOrder(rawValue: decoder.decodeInt32ForKey("order", orElse: 0)) ?? .regular - self.looping = MusicPlaybackSettingsLooping(rawValue: decoder.decodeInt32ForKey("looping", orElse: 0)) ?? .none - self.voicePlaybackRate = AudioPlaybackRate(rawValue: decoder.decodeInt32ForKey("voicePlaybackRate", orElse: AudioPlaybackRate.x1.rawValue)) ?? .x1 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.order = MusicPlaybackSettingsOrder(rawValue: try container.decode(Int32.self, forKey: "order")) ?? .regular + self.looping = MusicPlaybackSettingsLooping(rawValue: try container.decode(Int32.self, forKey: "looping")) ?? .none + self.voicePlaybackRate = AudioPlaybackRate(rawValue: try container.decodeIfPresent(Int32.self, forKey: "voicePlaybackRate") ?? AudioPlaybackRate.x1.rawValue) ?? .x1 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.order.rawValue, forKey: "order") - encoder.encodeInt32(self.looping.rawValue, forKey: "looping") - encoder.encodeInt32(self.voicePlaybackRate.rawValue, forKey: "voicePlaybackRate") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? MusicPlaybackSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.order.rawValue, forKey: "order") + try container.encode(self.looping.rawValue, forKey: "looping") + try container.encode(self.voicePlaybackRate.rawValue, forKey: "voicePlaybackRate") } public static func ==(lhs: MusicPlaybackSettings, rhs: MusicPlaybackSettings) -> Bool { @@ -93,12 +89,12 @@ public func updateMusicPlaybackSettingsInteractively(accountManager: AccountMana return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings, { entry in let currentSettings: MusicPlaybackSettings - if let entry = entry as? MusicPlaybackSettings { + if let entry = entry?.get(MusicPlaybackSettings.self) { currentSettings = entry } else { currentSettings = MusicPlaybackSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift b/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift index 45c1b0dcec..957cf8227f 100644 --- a/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct PresentationPasscodeSettings: PreferencesEntry, Equatable { +public struct PresentationPasscodeSettings: Codable, Equatable { public var enableBiometrics: Bool public var autolockTimeout: Int32? public var biometricsDomainState: Data? @@ -20,38 +20,22 @@ public struct PresentationPasscodeSettings: PreferencesEntry, Equatable { self.shareBiometricsDomainState = shareBiometricsDomainState } - public init(decoder: PostboxDecoder) { - self.enableBiometrics = decoder.decodeInt32ForKey("s", orElse: 0) != 0 - self.autolockTimeout = decoder.decodeOptionalInt32ForKey("al") - self.biometricsDomainState = decoder.decodeDataForKey("ds") - self.shareBiometricsDomainState = decoder.decodeDataForKey("sds") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.enableBiometrics = (try container.decode(Int32.self, forKey: "s")) != 0 + self.autolockTimeout = try container.decodeIfPresent(Int32.self, forKey: "al") + self.biometricsDomainState = try container.decodeIfPresent(Data.self, forKey: "ds") + self.shareBiometricsDomainState = try container.decodeIfPresent(Data.self, forKey: "sds") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.enableBiometrics ? 1 : 0, forKey: "s") - if let autolockTimeout = self.autolockTimeout { - encoder.encodeInt32(autolockTimeout, forKey: "al") - } else { - encoder.encodeNil(forKey: "al") - } - if let biometricsDomainState = self.biometricsDomainState { - encoder.encodeData(biometricsDomainState, forKey: "ds") - } else { - encoder.encodeNil(forKey: "ds") - } - if let shareBiometricsDomainState = self.shareBiometricsDomainState { - encoder.encodeData(shareBiometricsDomainState, forKey: "sds") - } else { - encoder.encodeNil(forKey: "sds") - } - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? PresentationPasscodeSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.enableBiometrics ? 1 : 0) as Int32, forKey: "s") + try container.encodeIfPresent(self.autolockTimeout, forKey: "al") + try container.encodeIfPresent(self.biometricsDomainState, forKey: "ds") + try container.encodeIfPresent(self.shareBiometricsDomainState, forKey: "sds") } public static func ==(lhs: PresentationPasscodeSettings, rhs: PresentationPasscodeSettings) -> Bool { @@ -84,11 +68,11 @@ public func updatePresentationPasscodeSettingsInteractively(accountManager: Acco public func updatePresentationPasscodeSettingsInternal(transaction: AccountManagerModifier, _ f: @escaping (PresentationPasscodeSettings) -> PresentationPasscodeSettings) { transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings, { entry in let currentSettings: PresentationPasscodeSettings - if let entry = entry as? PresentationPasscodeSettings { + if let entry = entry?.get(PresentationPasscodeSettings.self) { currentSettings = entry } else { currentSettings = PresentationPasscodeSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } diff --git a/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift b/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift index fa7a55fe50..7800057498 100644 --- a/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift @@ -262,51 +262,57 @@ public enum PresentationFontSize: Int32, CaseIterable { case medium = 6 } -public enum AutomaticThemeSwitchTimeBasedSetting: PostboxCoding, Equatable { +public enum AutomaticThemeSwitchTimeBasedSetting: Codable, Equatable { case manual(fromSeconds: Int32, toSeconds: Int32) case automatic(latitude: Double, longitude: Double, localizedName: String) - public init(decoder: PostboxDecoder) { - switch decoder.decodeInt32ForKey("_t", orElse: 0) { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + switch try container.decode(Int32.self, forKey: "_t") { case 0: - self = .manual(fromSeconds: decoder.decodeInt32ForKey("fromSeconds", orElse: 0), toSeconds: decoder.decodeInt32ForKey("toSeconds", orElse: 0)) + self = .manual(fromSeconds: try container.decode(Int32.self, forKey: "fromSeconds"), toSeconds: try container.decode(Int32.self, forKey: "toSeconds")) case 1: - self = .automatic(latitude: decoder.decodeDoubleForKey("latitude", orElse: 0.0), longitude: decoder.decodeDoubleForKey("longitude", orElse: 0.0), localizedName: decoder.decodeStringForKey("localizedName", orElse: "")) + self = .automatic(latitude: try container.decode(Double.self, forKey: "latitude"), longitude: try container.decode(Double.self, forKey: "longitude"), localizedName: try container.decode(String.self, forKey: "localizedName")) default: assertionFailure() self = .manual(fromSeconds: 0, toSeconds: 1) } } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + switch self { case let .manual(fromSeconds, toSeconds): - encoder.encodeInt32(0, forKey: "_t") - encoder.encodeInt32(fromSeconds, forKey: "fromSeconds") - encoder.encodeInt32(toSeconds, forKey: "toSeconds") + try container.encode(0 as Int32, forKey: "_t") + try container.encode(fromSeconds, forKey: "fromSeconds") + try container.encode(toSeconds, forKey: "toSeconds") case let .automatic(latitude, longitude, localizedName): - encoder.encodeInt32(1, forKey: "_t") - encoder.encodeDouble(latitude, forKey: "latitude") - encoder.encodeDouble(longitude, forKey: "longitude") - encoder.encodeString(localizedName, forKey: "localizedName") + try container.encode(1 as Int32, forKey: "_t") + try container.encode(latitude, forKey: "latitude") + try container.encode(longitude, forKey: "longitude") + try container.encode(localizedName, forKey: "localizedName") } } } -public enum AutomaticThemeSwitchTrigger: PostboxCoding, Equatable { +public enum AutomaticThemeSwitchTrigger: Codable, Equatable { case system case explicitNone case timeBased(setting: AutomaticThemeSwitchTimeBasedSetting) case brightness(threshold: Double) - public init(decoder: PostboxDecoder) { - switch decoder.decodeInt32ForKey("_t", orElse: 0) { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + switch try container.decode(Int32.self, forKey: "_t") { case 0: self = .system case 1: - self = .timeBased(setting: decoder.decodeObjectForKey("setting", decoder: { AutomaticThemeSwitchTimeBasedSetting(decoder: $0) }) as! AutomaticThemeSwitchTimeBasedSetting) + self = .timeBased(setting: try container.decode(AutomaticThemeSwitchTimeBasedSetting.self, forKey: "setting")) case 2: - self = .brightness(threshold: decoder.decodeDoubleForKey("threshold", orElse: 0.2)) + self = .brightness(threshold: try container.decode(Double.self, forKey: "threshold")) case 3: self = .explicitNone default: @@ -315,23 +321,25 @@ public enum AutomaticThemeSwitchTrigger: PostboxCoding, Equatable { } } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + switch self { case .system: - encoder.encodeInt32(0, forKey: "_t") + try container.encode(0 as Int32, forKey: "_t") case let .timeBased(setting): - encoder.encodeInt32(1, forKey: "_t") - encoder.encodeObject(setting, forKey: "setting") + try container.encode(1 as Int32, forKey: "_t") + try container.encode(setting, forKey: "setting") case let .brightness(threshold): - encoder.encodeInt32(2, forKey: "_t") - encoder.encodeDouble(threshold, forKey: "threshold") + try container.encode(2 as Int32, forKey: "_t") + try container.encode(threshold, forKey: "threshold") case .explicitNone: - encoder.encodeInt32(3, forKey: "_t") + try container.encode(3 as Int32, forKey: "_t") } } } -public struct AutomaticThemeSwitchSetting: PostboxCoding, Equatable { +public struct AutomaticThemeSwitchSetting: Codable, Equatable { public var trigger: AutomaticThemeSwitchTrigger public var theme: PresentationThemeReference @@ -340,20 +348,26 @@ public struct AutomaticThemeSwitchSetting: PostboxCoding, Equatable { self.theme = theme } - public init(decoder: PostboxDecoder) { - self.trigger = decoder.decodeObjectForKey("trigger", decoder: { AutomaticThemeSwitchTrigger(decoder: $0) }) as! AutomaticThemeSwitchTrigger - if let theme = decoder.decodeObjectForKey("theme_v2", decoder: { PresentationThemeReference(decoder: $0) }) as? PresentationThemeReference { - self.theme = theme - } else if let legacyValue = decoder.decodeOptionalInt32ForKey("theme") { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.trigger = try container.decode(AutomaticThemeSwitchTrigger.self, forKey: "trigger") + if let themeData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "theme_v2") { + self.theme = PresentationThemeReference(decoder: PostboxDecoder(buffer: MemoryBuffer(data: themeData.data))) + } else if let legacyValue = try container.decodeIfPresent(Int32.self, forKey: "theme") { self.theme = .builtin(PresentationBuiltinThemeReference(rawValue: legacyValue) ?? .nightAccent) } else { self.theme = .builtin(.nightAccent) } } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.trigger, forKey: "trigger") - encoder.encodeObject(self.theme, forKey: "theme_v2") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.trigger, forKey: "trigger") + + let themeData = PostboxEncoder().encodeObjectToRawData(self.theme) + try container.encode(themeData, forKey: "theme_v2") } } @@ -512,7 +526,7 @@ public struct PresentationThemeAccentColor: PostboxCoding, Equatable { } } -public struct PresentationChatBubbleSettings: PostboxCoding, Equatable { +public struct PresentationChatBubbleSettings: Codable, Equatable { public var mainRadius: Int32 public var auxiliaryRadius: Int32 public var mergeBubbleCorners: Bool @@ -525,20 +539,44 @@ public struct PresentationChatBubbleSettings: PostboxCoding, Equatable { self.mergeBubbleCorners = mergeBubbleCorners } - public init(decoder: PostboxDecoder) { - self.mainRadius = decoder.decodeInt32ForKey("mainRadius", orElse: 16) - self.auxiliaryRadius = decoder.decodeInt32ForKey("auxiliaryRadius", orElse: 8) - self.mergeBubbleCorners = decoder.decodeInt32ForKey("mergeBubbleCorners", orElse: 1) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.mainRadius = try container.decodeIfPresent(Int32.self, forKey: "mainRadius") ?? 16 + self.auxiliaryRadius = try container.decodeIfPresent(Int32.self, forKey: "auxiliaryRadius") ?? 8 + self.mergeBubbleCorners = (try container.decodeIfPresent(Int32.self, forKey: "mergeBubbleCorners") ?? 1) != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.mainRadius, forKey: "mainRadius") - encoder.encodeInt32(self.auxiliaryRadius, forKey: "auxiliaryRadius") - encoder.encodeInt32(self.mergeBubbleCorners ? 1 : 0, forKey: "mergeBubbleCorners") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.mainRadius, forKey: "mainRadius") + try container.encode(self.auxiliaryRadius, forKey: "auxiliaryRadius") + try container.encode((self.mergeBubbleCorners ? 1 : 0) as Int32, forKey: "mergeBubbleCorners") } } -public struct PresentationThemeSettings: PreferencesEntry { +public struct PresentationThemeSettings: Codable { + private struct DictionaryKey: Codable, Hashable { + var key: Int64 + + init(_ key: Int64) { + self.key = key + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.key = try container.decode(Int64.self, forKey: "k") + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.key, forKey: "k") + } + } + public var theme: PresentationThemeReference public var themeSpecificAccentColors: [Int64: PresentationThemeAccentColor] public var themeSpecificChatWallpapers: [Int64: TelegramWallpaper] @@ -602,54 +640,68 @@ public struct PresentationThemeSettings: PreferencesEntry { self.reduceMotion = reduceMotion } - public init(decoder: PostboxDecoder) { - self.theme = decoder.decodeObjectForKey("t", decoder: { PresentationThemeReference(decoder: $0) }) as? PresentationThemeReference ?? .builtin(.dayClassic) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) - self.themeSpecificChatWallpapers = decoder.decodeObjectDictionaryForKey("themeSpecificChatWallpapers", keyDecoder: { decoder in - return decoder.decodeInt64ForKey("k", orElse: 0) - }, valueDecoder: { decoder in - return TelegramWallpaper(decoder: decoder) - }) - - self.themeSpecificAccentColors = decoder.decodeObjectDictionaryForKey("themeSpecificAccentColors", keyDecoder: { decoder in - return decoder.decodeInt64ForKey("k", orElse: 0) - }, valueDecoder: { decoder in - return PresentationThemeAccentColor(decoder: decoder) - }) - - self.useSystemFont = decoder.decodeInt32ForKey("useSystemFont", orElse: 1) != 0 - let fontSize = PresentationFontSize(rawValue: decoder.decodeInt32ForKey("f", orElse: PresentationFontSize.regular.rawValue)) ?? .regular - self.fontSize = fontSize - self.listsFontSize = PresentationFontSize(rawValue: decoder.decodeInt32ForKey("lf", orElse: PresentationFontSize.regular.rawValue)) ?? fontSize - self.chatBubbleSettings = decoder.decodeObjectForKey("chatBubbleSettings", decoder: { PresentationChatBubbleSettings(decoder: $0) }) as? PresentationChatBubbleSettings ?? PresentationChatBubbleSettings.default - self.automaticThemeSwitchSetting = (decoder.decodeObjectForKey("automaticThemeSwitchSetting", decoder: { AutomaticThemeSwitchSetting(decoder: $0) }) as? AutomaticThemeSwitchSetting) ?? AutomaticThemeSwitchSetting(trigger: .system, theme: .builtin(.night)) - self.largeEmoji = decoder.decodeBoolForKey("largeEmoji", orElse: true) - self.reduceMotion = decoder.decodeBoolForKey("reduceMotion", orElse: false) - } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.theme, forKey: "t") - encoder.encodeObjectDictionary(self.themeSpecificAccentColors, forKey: "themeSpecificAccentColors", keyEncoder: { key, encoder in - encoder.encodeInt64(key, forKey: "k") - }) - encoder.encodeObjectDictionary(self.themeSpecificChatWallpapers, forKey: "themeSpecificChatWallpapers", keyEncoder: { key, encoder in - encoder.encodeInt64(key, forKey: "k") - }) - encoder.encodeInt32(self.useSystemFont ? 1 : 0, forKey: "useSystemFont") - encoder.encodeInt32(self.fontSize.rawValue, forKey: "f") - encoder.encodeInt32(self.listsFontSize.rawValue, forKey: "lf") - encoder.encodeObject(self.chatBubbleSettings, forKey: "chatBubbleSettings") - encoder.encodeObject(self.automaticThemeSwitchSetting, forKey: "automaticThemeSwitchSetting") - encoder.encodeBool(self.largeEmoji, forKey: "largeEmoji") - encoder.encodeBool(self.reduceMotion, forKey: "reduceMotion") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? PresentationThemeSettings { - return self == to + if let themeData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "t"), let theme = PostboxDecoder(buffer: MemoryBuffer(data: themeData.data)).decodeRootObjectWithHash(hash: themeData.typeHash) as? PresentationThemeReference { + self.theme = theme } else { - return false + self.theme = .builtin(.dayClassic) } + + let themeSpecificChatWallpapersDict = try container.decode([DictionaryKey: AdaptedPostboxDecoder.RawObjectData].self, forKey: "themeSpecificChatWallpapers") + var mappedThemeSpecificChatWallpapers: [Int64: TelegramWallpaper] = [:] + for (key, value) in themeSpecificChatWallpapersDict { + let innerDecoder = PostboxDecoder(buffer: MemoryBuffer(data: value.data)) + mappedThemeSpecificChatWallpapers[key.key] = TelegramWallpaper(decoder: innerDecoder) + } + self.themeSpecificChatWallpapers = mappedThemeSpecificChatWallpapers + + let themeSpecificAccentColorsDict = try container.decode([DictionaryKey: AdaptedPostboxDecoder.RawObjectData].self, forKey: "themeSpecificAccentColors") + var mappedThemeSpecificAccentColors: [Int64: PresentationThemeAccentColor] = [:] + for (key, value) in themeSpecificAccentColorsDict { + let innerDecoder = PostboxDecoder(buffer: MemoryBuffer(data: value.data)) + mappedThemeSpecificAccentColors[key.key] = PresentationThemeAccentColor(decoder: innerDecoder) + } + self.themeSpecificAccentColors = mappedThemeSpecificAccentColors + + self.useSystemFont = (try container.decodeIfPresent(Int32.self, forKey: "useSystemFont") ?? 1) != 0 + + let fontSize = PresentationFontSize(rawValue: try container.decodeIfPresent(Int32.self, forKey: "f") ?? PresentationFontSize.regular.rawValue) ?? .regular + self.fontSize = fontSize + self.listsFontSize = PresentationFontSize(rawValue: try container.decodeIfPresent(Int32.self, forKey: "lf") ?? PresentationFontSize.regular.rawValue) ?? fontSize + + self.chatBubbleSettings = try container.decodeIfPresent(PresentationChatBubbleSettings.self, forKey: "chatBubbleSettings") ?? PresentationChatBubbleSettings.default + self.automaticThemeSwitchSetting = try container.decodeIfPresent(AutomaticThemeSwitchSetting.self, forKey: "automaticThemeSwitchSetting") ?? AutomaticThemeSwitchSetting(trigger: .system, theme: .builtin(.night)) + + self.largeEmoji = try container.decodeIfPresent(Bool.self, forKey: "largeEmoji") ?? true + self.reduceMotion = try container.decodeIfPresent(Bool.self, forKey: "reduceMotion") ?? false + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(PostboxEncoder().encodeObjectToRawData(self.theme), forKey: "t") + + var mappedThemeSpecificAccentColors: [DictionaryKey: AdaptedPostboxEncoder.RawObjectData] = [:] + for (key, value) in self.themeSpecificAccentColors { + mappedThemeSpecificAccentColors[DictionaryKey(key)] = PostboxEncoder().encodeObjectToRawData(value) + } + try container.encode(mappedThemeSpecificAccentColors, forKey: "themeSpecificAccentColors") + + var mappedThemeSpecificChatWallpapers: [DictionaryKey: AdaptedPostboxEncoder.RawObjectData] = [:] + for (key, value) in self.themeSpecificChatWallpapers { + mappedThemeSpecificChatWallpapers[DictionaryKey(key)] = PostboxEncoder().encodeObjectToRawData(value) + } + try container.encode(mappedThemeSpecificChatWallpapers, forKey: "themeSpecificChatWallpapers") + + try container.encode((self.useSystemFont ? 1 : 0) as Int32, forKey: "useSystemFont") + try container.encode(self.fontSize.rawValue, forKey: "f") + try container.encode(self.listsFontSize.rawValue, forKey: "lf") + try container.encode(self.chatBubbleSettings, forKey: "chatBubbleSettings") + try container.encode(self.automaticThemeSwitchSetting, forKey: "automaticThemeSwitchSetting") + try container.encode(self.largeEmoji, forKey: "largeEmoji") + try container.encode(self.reduceMotion, forKey: "reduceMotion") } public static func ==(lhs: PresentationThemeSettings, rhs: PresentationThemeSettings) -> Bool { @@ -697,12 +749,12 @@ public func updatePresentationThemeSettingsInteractively(accountManager: Account return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings, { entry in let currentSettings: PresentationThemeSettings - if let entry = entry as? PresentationThemeSettings { + if let entry = entry?.get(PresentationThemeSettings.self) { currentSettings = entry } else { currentSettings = PresentationThemeSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift b/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift index dff99b50bf..ea3a4a9b9a 100644 --- a/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift +++ b/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift @@ -34,7 +34,7 @@ public func renderedTotalUnreadCount(accountManager: AccountManager Bool { - if let to = to as? StickerSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.emojiStickerSuggestionMode.rawValue, forKey: "emojiStickerSuggestionMode") + try container.encode(self.loopAnimatedStickers, forKey: "loopAnimatedStickers") } public static func ==(lhs: StickerSettings, rhs: StickerSettings) -> Bool { @@ -57,12 +53,12 @@ public func updateStickerSettingsInteractively(accountManager: AccountManager Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.stickerSettings, { entry in let currentSettings: StickerSettings - if let entry = entry as? StickerSettings { + if let entry = entry?.get(StickerSettings.self) { currentSettings = entry } else { currentSettings = StickerSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift b/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift index 3dc6a49852..fa6d5954a7 100644 --- a/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift @@ -29,7 +29,7 @@ public enum VoiceCallDataSaving: Int32 { case `default` } -public struct VoiceCallSettings: PreferencesEntry, Equatable { +public struct VoiceCallSettings: Codable, Equatable { public var dataSaving: VoiceCallDataSaving public var enableSystemIntegration: Bool @@ -42,22 +42,18 @@ public struct VoiceCallSettings: PreferencesEntry, Equatable { self.enableSystemIntegration = enableSystemIntegration } - public init(decoder: PostboxDecoder) { - self.dataSaving = VoiceCallDataSaving(rawValue: decoder.decodeInt32ForKey("ds", orElse: 0))! - self.enableSystemIntegration = decoder.decodeInt32ForKey("enableSystemIntegration", orElse: 1) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.dataSaving = VoiceCallDataSaving(rawValue: try container.decode(Int32.self, forKey: "ds")) ?? .default + self.enableSystemIntegration = (try container.decode(Int32.self, forKey: "enableSystemIntegration")) != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.dataSaving.rawValue, forKey: "ds") - encoder.encodeInt32(self.enableSystemIntegration ? 1 : 0, forKey: "enableSystemIntegration") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? VoiceCallSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.dataSaving.rawValue, forKey: "ds") + try container.encode((self.enableSystemIntegration ? 1 : 0) as Int32, forKey: "enableSystemIntegration") } public static func ==(lhs: VoiceCallSettings, rhs: VoiceCallSettings) -> Bool { @@ -75,12 +71,12 @@ public func updateVoiceCallSettingsSettingsInteractively(accountManager: Account return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.voiceCallSettings, { entry in let currentSettings: VoiceCallSettings - if let entry = entry as? VoiceCallSettings { + if let entry = entry?.get(VoiceCallSettings.self) { currentSettings = entry } else { currentSettings = VoiceCallSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/VoipDerivedState.swift b/submodules/TelegramUIPreferences/Sources/VoipDerivedState.swift index eb11fd9455..cf75372566 100644 --- a/submodules/TelegramUIPreferences/Sources/VoipDerivedState.swift +++ b/submodules/TelegramUIPreferences/Sources/VoipDerivedState.swift @@ -1,8 +1,9 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit -public struct VoipDerivedState: Equatable, PreferencesEntry { +public struct VoipDerivedState: Codable, Equatable { public var data: Data public static var `default`: VoipDerivedState { @@ -13,20 +14,16 @@ public struct VoipDerivedState: Equatable, PreferencesEntry { self.data = data } - public init(decoder: PostboxDecoder) { - self.data = decoder.decodeDataForKey("data") ?? Data() + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.data = try container.decode(Data.self, forKey: "data") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeData(self.data, forKey: "data") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? VoipDerivedState { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.data, forKey: "data") } } @@ -34,12 +31,12 @@ public func updateVoipDerivedStateInteractively(postbox: Postbox, _ f: @escaping return postbox.transaction { transaction -> Void in transaction.updatePreferencesEntry(key: ApplicationSpecificPreferencesKeys.voipDerivedState, { entry in let currentSettings: VoipDerivedState - if let entry = entry as? VoipDerivedState { + if let entry = entry?.get(VoipDerivedState.self) { currentSettings = entry } else { currentSettings = .default } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift b/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift index c73fa77c0e..99ff7f799e 100644 --- a/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct WatchPresetSettings: PreferencesEntry, Equatable { +public struct WatchPresetSettings: Codable, Equatable { public var customPresets: [String : String] public static var defaultSettings: WatchPresetSettings { @@ -14,9 +14,11 @@ public struct WatchPresetSettings: PreferencesEntry, Equatable { self.customPresets = presets } - public init(decoder: PostboxDecoder) { - let keys = decoder.decodeStringArrayForKey("presetKeys") - let values = decoder.decodeStringArrayForKey("presetValues") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let keys = try container.decode([String].self, forKey: "presetKeys") + let values = try container.decode([String].self, forKey: "presetValues") if keys.count == values.count { var presets: [String : String] = [:] for i in 0 ..< keys.count { @@ -28,7 +30,9 @@ public struct WatchPresetSettings: PreferencesEntry, Equatable { } } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + let keys = self.customPresets.keys.sorted() let values = keys.reduce([String]()) { (values, index) in var values = values @@ -37,16 +41,8 @@ public struct WatchPresetSettings: PreferencesEntry, Equatable { } return values } - encoder.encodeStringArray(keys, forKey: "presetKeys") - encoder.encodeStringArray(values, forKey: "presetValues") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? WatchPresetSettings { - return self == to - } else { - return false - } + try container.encode(keys, forKey: "presetKeys") + try container.encode(values, forKey: "presetValues") } public static func ==(lhs: WatchPresetSettings, rhs: WatchPresetSettings) -> Bool { @@ -58,12 +54,12 @@ public func updateWatchPresetSettingsInteractively(accountManager: AccountManage return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.watchPresetSettings, { entry in let currentSettings: WatchPresetSettings - if let entry = entry as? WatchPresetSettings { + if let entry = entry?.get(WatchPresetSettings.self) { currentSettings = entry } else { currentSettings = WatchPresetSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift b/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift index d2b0082fef..0739d93e81 100644 --- a/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift @@ -3,7 +3,7 @@ import Postbox import TelegramCore import SwiftSignalKit -public struct WebBrowserSettings: PreferencesEntry, Equatable { +public struct WebBrowserSettings: Codable, Equatable { public let defaultWebBrowser: String? public static var defaultSettings: WebBrowserSettings { @@ -14,24 +14,16 @@ public struct WebBrowserSettings: PreferencesEntry, Equatable { self.defaultWebBrowser = defaultWebBrowser } - public init(decoder: PostboxDecoder) { - self.defaultWebBrowser = decoder.decodeOptionalStringForKey("defaultWebBrowser") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.defaultWebBrowser = try? container.decodeIfPresent(String.self, forKey: "defaultWebBrowser") } - public func encode(_ encoder: PostboxEncoder) { - if let defaultWebBrowser = self.defaultWebBrowser { - encoder.encodeString(defaultWebBrowser, forKey: "defaultWebBrowser") - } else { - encoder.encodeNil(forKey: "defaultWebBrowser") - } - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? WebBrowserSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encodeIfPresent(self.defaultWebBrowser, forKey: "defaultWebBrowser") } public static func ==(lhs: WebBrowserSettings, rhs: WebBrowserSettings) -> Bool { @@ -47,12 +39,12 @@ public func updateWebBrowserSettingsInteractively(accountManager: AccountManager return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.webBrowserSettings, { entry in let currentSettings: WebBrowserSettings - if let entry = entry as? WebBrowserSettings { + if let entry = entry?.get(WebBrowserSettings.self) { currentSettings = entry } else { currentSettings = WebBrowserSettings.defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift b/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift index 99c3c2b35e..09debb4d1c 100644 --- a/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift @@ -8,7 +8,7 @@ public enum WebSearchScope: Int32 { case gifs } -public struct WebSearchSettings: Equatable, PreferencesEntry { +public struct WebSearchSettings: Codable, Equatable { public var scope: WebSearchScope public static var defaultSettings: WebSearchSettings { @@ -19,20 +19,16 @@ public struct WebSearchSettings: Equatable, PreferencesEntry { self.scope = scope } - public init(decoder: PostboxDecoder) { - self.scope = WebSearchScope(rawValue: decoder.decodeInt32ForKey("scope", orElse: 0)) ?? .images + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.scope = WebSearchScope(rawValue: try container.decode(Int32.self, forKey: "scope")) ?? .images } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.scope.rawValue, forKey: "scope") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? WebSearchSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.scope.rawValue, forKey: "scope") } } @@ -40,12 +36,12 @@ public func updateWebSearchSettingsInteractively(accountManager: AccountManager< return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.webSearchSettings, { entry in let currentSettings: WebSearchSettings - if let entry = entry as? WebSearchSettings { + if let entry = entry?.get(WebSearchSettings.self) { currentSettings = entry } else { currentSettings = .defaultSettings } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } } diff --git a/submodules/TelegramUIPreferences/Sources/WidgetSettings.swift b/submodules/TelegramUIPreferences/Sources/WidgetSettings.swift index c2965f2c42..f54174921d 100644 --- a/submodules/TelegramUIPreferences/Sources/WidgetSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WidgetSettings.swift @@ -1,9 +1,9 @@ - import Foundation import Postbox +import TelegramCore import SwiftSignalKit -public struct WidgetSettings: PreferencesEntry, Equatable { +public struct WidgetSettings: Codable, Equatable { public var useHints: Bool public var peers: [PeerId] @@ -22,22 +22,18 @@ public struct WidgetSettings: PreferencesEntry, Equatable { self.peers = peers } - public init(decoder: PostboxDecoder) { - self.useHints = decoder.decodeBoolForKey("useHints", orElse: true) - self.peers = decoder.decodeInt64ArrayForKey("peers").map { PeerId($0) } + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.useHints = try container.decode(Bool.self, forKey: "useHints") + self.peers = (try container.decode([Int64].self, forKey: "peers")).map { PeerId($0) } } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeBool(self.useHints, forKey: "useHints") - encoder.encodeInt64Array(self.peers.map { $0.toInt64() }, forKey: "peers") - } - - public func isEqual(to: PreferencesEntry) -> Bool { - if let to = to as? WidgetSettings { - return self == to - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.useHints, forKey: "useHints") + try container.encode(self.peers.map { $0.toInt64() } as [Int64], forKey: "peers") } } @@ -51,11 +47,11 @@ public func updateWidgetSettingsInteractively(postbox: Postbox, _ f: @escaping ( public func updateWidgetSettingsInteractively(transaction: Transaction, _ f: @escaping (WidgetSettings) -> WidgetSettings) { transaction.updatePreferencesEntry(key: ApplicationSpecificPreferencesKeys.widgetSettings, { entry in let currentSettings: WidgetSettings - if let entry = entry as? WidgetSettings { + if let entry = entry?.get(WidgetSettings.self) { currentSettings = entry } else { currentSettings = .default } - return f(currentSettings) + return PreferencesEntry(f(currentSettings)) }) } diff --git a/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.h b/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.h index e34181f313..c592dfc1b2 100644 --- a/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.h +++ b/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.h @@ -18,6 +18,13 @@ typedef NS_OPTIONS(NSUInteger, UIResponderDisableAutomaticKeyboardHandling) { @end +@interface UIApplication (Additions) + +- (void)internalSetStatusBarStyle:(UIStatusBarStyle)style animated:(BOOL)animated; +- (void)internalSetStatusBarHidden:(BOOL)hidden animation:(UIStatusBarAnimation)animation; + +@end + @interface UIView (Navigation) @property (nonatomic) bool disablesInteractiveTransitionGestureRecognizer; diff --git a/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.m b/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.m index a59590d627..d5a8a31551 100644 --- a/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.m +++ b/submodules/UIKitRuntimeUtils/Source/UIKitRuntimeUtils/UIViewController+Navigation.m @@ -238,6 +238,24 @@ static bool notyfyingShiftState = false; @end +@implementation UIApplication (Additions) + +- (void)internalSetStatusBarStyle:(UIStatusBarStyle)style animated:(BOOL)animated { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self setStatusBarStyle:style animated:animated]; +#pragma clang diagnostic pop +} + +- (void)internalSetStatusBarHidden:(BOOL)hidden animation:(UIStatusBarAnimation)animation { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self setStatusBarHidden:hidden withAnimation:animation]; +#pragma clang diagnostic pop +} + +@end + @implementation UIView (Navigation) - (bool)disablesInteractiveTransitionGestureRecognizer { diff --git a/submodules/UrlHandling/Sources/UrlHandling.swift b/submodules/UrlHandling/Sources/UrlHandling.swift index bed77ec35c..17d07d9177 100644 --- a/submodules/UrlHandling/Sources/UrlHandling.swift +++ b/submodules/UrlHandling/Sources/UrlHandling.swift @@ -564,7 +564,7 @@ public func resolveUrlImpl(context: AccountContext, peerId: PeerId?, url: String return ApplicationSpecificNotice.getSecretChatLinkPreviews(accountManager: context.sharedContext.accountManager) |> mapToSignal { linkPreviews -> Signal in return context.account.postbox.transaction { transaction -> Signal in - let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration) as? AppConfiguration ?? AppConfiguration.defaultValue + let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue let urlHandlingConfiguration = UrlHandlingConfiguration.with(appConfiguration: appConfiguration) var skipUrlAuth = skipUrlAuth diff --git a/submodules/WatchBridge/Sources/WatchCommunicationManager.swift b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift index fdc6f30dfa..4672c1a99b 100644 --- a/submodules/WatchBridge/Sources/WatchCommunicationManager.swift +++ b/submodules/WatchBridge/Sources/WatchCommunicationManager.swift @@ -96,7 +96,7 @@ public final class WatchCommunicationManager { strongSelf.presets.set(context.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.watchPresetSettings]) |> map({ sharedData -> WatchPresetSettings in - return (sharedData.entries[ApplicationSpecificSharedDataKeys.watchPresetSettings] as? WatchPresetSettings) ?? WatchPresetSettings.defaultSettings + return sharedData.entries[ApplicationSpecificSharedDataKeys.watchPresetSettings]?.get(WatchPresetSettings.self) ?? WatchPresetSettings.defaultSettings })) } else { strongSelf.accountContext.set(.single(nil)) diff --git a/submodules/WebSearchUI/Sources/WebSearchController.swift b/submodules/WebSearchUI/Sources/WebSearchController.swift index 7652ef49a9..819cd31677 100644 --- a/submodules/WebSearchUI/Sources/WebSearchController.swift +++ b/submodules/WebSearchUI/Sources/WebSearchController.swift @@ -182,7 +182,7 @@ public final class WebSearchController: ViewController { let settings = self.context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.webSearchSettings]) |> map { sharedData -> WebSearchSettings in - if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webSearchSettings] as? WebSearchSettings { + if let current = sharedData.entries[ApplicationSpecificSharedDataKeys.webSearchSettings]?.get(WebSearchSettings.self) { return current } else { return WebSearchSettings.defaultSettings @@ -191,7 +191,7 @@ public final class WebSearchController: ViewController { let gifProvider = self.context.account.postbox.preferencesView(keys: [PreferencesKeys.appConfiguration]) |> map { view -> String? in - guard let appConfiguration = view.values[PreferencesKeys.appConfiguration] as? AppConfiguration else { + guard let appConfiguration = view.values[PreferencesKeys.appConfiguration]?.get(AppConfiguration.self) else { return nil } let configuration = WebSearchConfiguration(appConfiguration: appConfiguration) diff --git a/submodules/WidgetSetupScreen/Sources/WidgetSetupScreen.swift b/submodules/WidgetSetupScreen/Sources/WidgetSetupScreen.swift index c358864c6a..ebe97ba61b 100644 --- a/submodules/WidgetSetupScreen/Sources/WidgetSetupScreen.swift +++ b/submodules/WidgetSetupScreen/Sources/WidgetSetupScreen.swift @@ -293,7 +293,7 @@ public func widgetSetupScreen(context: AccountContext) -> ViewController { ]) |> mapToSignal { views -> Signal in let widgetSettings: WidgetSettings - if let view = views.views[preferencesKey] as? PreferencesView, let value = view.values[ApplicationSpecificPreferencesKeys.widgetSettings] as? WidgetSettings { + if let view = views.views[preferencesKey] as? PreferencesView, let value = view.values[ApplicationSpecificPreferencesKeys.widgetSettings]?.get(WidgetSettings.self) { widgetSettings = value } else { widgetSettings = .default