From bf253eec46fcd97d0ae0135ff0affba1244540ca Mon Sep 17 00:00:00 2001 From: Ali <> Date: Thu, 12 Aug 2021 16:41:11 +0200 Subject: [PATCH] Refactoring --- Telegram/SiriIntents/IntentHandler.swift | 43 +++---- .../Sources/AccountContext.swift | 2 +- submodules/AppLock/BUILD | 1 + submodules/AppLock/Sources/AppLock.swift | 5 +- ...onSequenceCountrySelectionController.swift | 4 +- .../Sources/DebugAccountsController.swift | 6 +- .../Sources/PasscodeEntryController.swift | 5 +- .../Sources/PasscodeEntryControllerNode.swift | 4 +- .../Postbox/Sources/AccountManager.swift | 110 +++++++++--------- .../Sources/AccountManagerAtomicState.swift | 16 +-- .../Sources/AccountManagerMetadataTable.swift | 63 +++++----- .../Sources/AccountManagerRecordTable.swift | 32 ++--- .../Postbox/Sources/AccountRecord.swift | 56 +++------ .../Postbox/Sources/AccountRecordsView.swift | 22 ++-- .../Postbox/Sources/AccountSharedData.swift | 10 +- submodules/Postbox/Sources/Coding.swift | 66 ++++++++++- .../Postbox/Sources/NoticeEntryView.swift | 12 +- .../Utils/Decoder/AdaptedPostboxDecoder.swift | 12 +- ...AdaptedPostboxKeyedDecodingContainer.swift | 8 ++ .../ProxyListSettingsController.swift | 2 +- .../ProxyServerActionSheetController.swift | 10 +- .../ProxyServerSettingsController.swift | 2 +- .../Sources/PresentationCallManager.swift | 4 +- .../Sources/Account/Account.swift | 8 +- .../Sources/Account/AccountManager.swift | 95 ++++++++++++--- .../TelegramCore/Sources/Authorization.swift | 25 ++-- .../Settings/AutodownloadSettings.swift | 2 +- .../Settings/CacheStorageSettings.swift | 2 +- .../Sources/Settings/LoggingSettings.swift | 2 +- .../Sources/Settings/ProxySettings.swift | 4 +- .../State/AccountStateManagementUtils.swift | 2 +- .../Sources/State/AccountStateManager.swift | 4 +- .../ManagedAutodownloadSettingsUpdates.swift | 2 +- .../State/ManagedConfigurationUpdates.swift | 2 +- ...ManagedLocalizationUpdatesOperations.swift | 8 +- .../SyncCore_AccountBackupDataAttribute.swift | 30 ++--- ...SyncCore_AccountEnvironmentAttribute.swift | 29 +++-- .../SyncCore_AccountSortOrderAttribute.swift | 27 +++-- .../SyncCore_LoggedOutAccountAttribute.swift | 12 +- .../SyncCore/SyncCore_wallapersState.swift | 2 +- .../TelegramEngine/Auth/AuthTransfer.swift | 2 +- .../Auth/TelegramEngineAuth.swift | 2 +- .../Localization/Countries.swift | 2 +- .../Localization/Localizations.swift | 2 +- .../TelegramEngineLocalization.swift | 8 +- submodules/TelegramCore/Sources/Themes.swift | 16 +-- submodules/TelegramNotices/BUILD | 1 + .../TelegramNotices/Sources/Notices.swift | 103 ++++++++-------- .../Sources/PresentationData.swift | 4 +- .../TelegramUI/Sources/AppDelegate.swift | 10 +- .../Sources/ApplicationContext.swift | 2 +- ...uthorizationSequenceSplashController.swift | 4 +- .../TelegramUI/Sources/ChatLinkPreview.swift | 3 +- .../Sources/FetchCachedRepresentations.swift | 2 +- .../Sources/ManageSharedAccountInfo.swift | 2 +- .../TelegramUI/Sources/MediaManager.swift | 4 +- .../Sources/NotificationContentContext.swift | 2 +- .../Sources/OverlayPlayerControlsNode.swift | 4 +- .../Sources/ShareExtensionContext.swift | 2 +- .../Sources/SharedAccountContext.swift | 34 ++++-- .../Sources/SharedNotificationManager.swift | 2 +- .../Sources/SpotlightContacts.swift | 6 +- .../Sources/StoreDownloadedMedia.swift | 4 +- .../TelegramUI/Sources/UpgradedAccounts.swift | 4 +- .../Sources/CallListSettings.swift | 3 +- .../ContactSynchronizationSettings.swift | 3 +- .../Sources/ExperimentalSettings.swift | 3 +- .../Sources/ExperimentalUISettings.swift | 3 +- .../Sources/GeneratedMediaStoreSettings.swift | 3 +- .../Sources/InAppNotificationSettings.swift | 2 +- .../InstantPagePresentationSettings.swift | 3 +- .../Sources/IntentsSettings.swift | 3 +- .../Sources/MediaAutoDownloadSettings.swift | 2 +- .../Sources/MediaInputSettings.swift | 3 +- .../Sources/MusicPlaybackSettings.swift | 3 +- .../PresentationPasscodeSettings.swift | 5 +- .../Sources/PresentationThemeSettings.swift | 2 +- .../Sources/RenderedTotalUnreadCount.swift | 3 +- .../Sources/StickerSettings.swift | 3 +- .../Sources/VoiceCallSettings.swift | 2 +- .../Sources/WatchPresetSettings.swift | 3 +- .../Sources/WebBrowserSettings.swift | 3 +- .../Sources/WebSearchSettings.swift | 3 +- .../Sources/WallpaperResources.swift | 16 +-- 84 files changed, 604 insertions(+), 443 deletions(-) diff --git a/Telegram/SiriIntents/IntentHandler.swift b/Telegram/SiriIntents/IntentHandler.swift index f492ef9884..452362d86f 100644 --- a/Telegram/SiriIntents/IntentHandler.swift +++ b/Telegram/SiriIntents/IntentHandler.swift @@ -34,7 +34,7 @@ private struct ApplicationSettings { let logging: LoggingSettings } -private func applicationSettings(accountManager: AccountManager) -> Signal { +private func applicationSettings(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> ApplicationSettings in let loggingSettings: LoggingSettings if let value = transaction.getSharedData(SharedDataKeys.loggingSettings) as? LoggingSettings { @@ -79,7 +79,7 @@ class DefaultIntentHandler: INExtension, INSendMessageIntentHandling, INSearchFo private let searchDisposable = MetaDisposable() private var rootPath: String? - private var accountManager: AccountManager? + private var accountManager: AccountManager? private var encryptionParameters: ValueBoxEncryptionParameters? private var appGroupUrl: URL? @@ -121,7 +121,7 @@ class DefaultIntentHandler: INExtension, INSendMessageIntentHandling, INSearchFo let appVersion = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "unknown" initializeAccountManagement() - let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) + let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) self.accountManager = accountManager let deviceSpecificEncryptionParameters = BuildConfig.deviceSpecificEncryptionParameters(rootPath, baseAppBundleId: baseAppBundleId) @@ -134,25 +134,22 @@ class DefaultIntentHandler: INExtension, INSendMessageIntentHandling, INSearchFo var result: [(AccountRecordId, Int, PeerId, Bool)] = [] for record in view.records { let isLoggedOut = record.attributes.contains(where: { attribute in - return attribute is LoggedOutAccountAttribute - }) - if isLoggedOut { - continue - } - /*let isTestingEnvironment = record.attributes.contains(where: { attribute in - if let attribute = attribute as? AccountEnvironmentAttribute, case .test = attribute.environment { + if case .loggedOut = attribute { return true } else { return false } - })*/ + }) + if isLoggedOut { + continue + } var backupData: AccountBackupData? var sortIndex: Int32 = 0 for attribute in record.attributes { - if let attribute = attribute as? AccountSortOrderAttribute { - sortIndex = attribute.order - } else if let attribute = attribute as? AccountBackupDataAttribute { - backupData = attribute.data + if case let .sortOrder(sortOrder) = attribute { + sortIndex = sortOrder.order + } else if case let .backupData(backupDataValue) = attribute { + backupData = backupDataValue.data } } if let backupData = backupData { @@ -894,12 +891,16 @@ private final class WidgetIntentHandler { let encryptionParameters = ValueBoxEncryptionParameters(forceEncryptionIfNoSet: false, key: ValueBoxEncryptionParameters.Key(data: deviceSpecificEncryptionParameters.key)!, salt: ValueBoxEncryptionParameters.Salt(data: deviceSpecificEncryptionParameters.salt)!) self.encryptionParameters = encryptionParameters - let view = AccountManager.getCurrentRecords(basePath: rootPath + "/accounts-metadata") + let view = AccountManager.getCurrentRecords(basePath: rootPath + "/accounts-metadata") var result: [(AccountRecordId, Int, PeerId, Bool)] = [] for record in view.records { let isLoggedOut = record.attributes.contains(where: { attribute in - return attribute is LoggedOutAccountAttribute + if case .loggedOut = attribute { + return true + } else { + return false + } }) if isLoggedOut { continue @@ -907,10 +908,10 @@ private final class WidgetIntentHandler { var backupData: AccountBackupData? var sortIndex: Int32 = 0 for attribute in record.attributes { - if let attribute = attribute as? AccountSortOrderAttribute { - sortIndex = attribute.order - } else if let attribute = attribute as? AccountBackupDataAttribute { - backupData = attribute.data + if case let .sortOrder(sortOrder) = attribute { + sortIndex = sortOrder.order + } else if case let .backupData(backupDataValue) = attribute { + backupData = backupDataValue.data } } if let backupData = backupData { diff --git a/submodules/AccountContext/Sources/AccountContext.swift b/submodules/AccountContext/Sources/AccountContext.swift index 610862991c..9a4849cb99 100644 --- a/submodules/AccountContext/Sources/AccountContext.swift +++ b/submodules/AccountContext/Sources/AccountContext.swift @@ -552,7 +552,7 @@ public protocol SharedAccountContext: AnyObject { var sharedContainerPath: String { get } var basePath: String { get } var mainWindow: Window1? { get } - var accountManager: AccountManager { get } + var accountManager: AccountManager { get } var appLockContext: AppLockContext { get } var currentPresentationData: Atomic { get } diff --git a/submodules/AppLock/BUILD b/submodules/AppLock/BUILD index ff6e8e8147..a4e95c2e8b 100644 --- a/submodules/AppLock/BUILD +++ b/submodules/AppLock/BUILD @@ -14,6 +14,7 @@ swift_library( "//submodules/Display:Display", "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", "//submodules/TelegramPresentationData:TelegramPresentationData", "//submodules/MonotonicTime:MonotonicTime", "//submodules/PasscodeUI:PasscodeUI", diff --git a/submodules/AppLock/Sources/AppLock.swift b/submodules/AppLock/Sources/AppLock.swift index 6fe5ddef16..51e480825e 100644 --- a/submodules/AppLock/Sources/AppLock.swift +++ b/submodules/AppLock/Sources/AppLock.swift @@ -1,6 +1,7 @@ import Foundation import UIKit import Postbox +import TelegramCore import Display import SwiftSignalKit import MonotonicTime @@ -65,7 +66,7 @@ public final class AppLockContextImpl: AppLockContext { private let syncQueue = Queue() private let applicationBindings: TelegramApplicationBindings - private let accountManager: AccountManager + private let accountManager: AccountManager private let presentationDataSignal: Signal private let window: Window1? private let rootController: UIViewController? @@ -90,7 +91,7 @@ public final class AppLockContextImpl: AppLockContext { private var lastActiveTimestamp: Double? private var lastActiveValue: Bool = false - public init(rootPath: String, window: Window1?, rootController: UIViewController?, applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, presentationDataSignal: Signal, lockIconInitialFrame: @escaping () -> CGRect?) { + public init(rootPath: String, window: Window1?, rootController: UIViewController?, applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, presentationDataSignal: Signal, lockIconInitialFrame: @escaping () -> CGRect?) { assert(Queue.mainQueue().isCurrent()) self.applicationBindings = applicationBindings diff --git a/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift b/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift index a71f96627e..938e641801 100644 --- a/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift +++ b/submodules/CountrySelectionUI/Sources/AuthorizationSequenceCountrySelectionController.swift @@ -69,7 +69,7 @@ private func loadCountryCodes() -> [Country] { private var countryCodes: [Country] = loadCountryCodes() private var countryCodesByPrefix: [String: (Country, Country.CountryCode)] = [:] -public func loadServerCountryCodes(accountManager: AccountManager, engine: TelegramEngineUnauthorized, completion: @escaping () -> Void) { +public func loadServerCountryCodes(accountManager: AccountManager, engine: TelegramEngineUnauthorized, completion: @escaping () -> Void) { let _ = (engine.localization.getCountriesList(accountManager: accountManager, langCode: nil) |> deliverOnMainQueue).start(next: { countries in countryCodes = countries @@ -93,7 +93,7 @@ public func loadServerCountryCodes(accountManager: AccountManager, engine: Teleg }) } -public func loadServerCountryCodes(accountManager: AccountManager, engine: TelegramEngine, completion: @escaping () -> Void) { +public func loadServerCountryCodes(accountManager: AccountManager, engine: TelegramEngine, completion: @escaping () -> Void) { let _ = (engine.localization.getCountriesList(accountManager: accountManager, langCode: nil) |> deliverOnMainQueue).start(next: { countries in countryCodes = countries diff --git a/submodules/DebugSettingsUI/Sources/DebugAccountsController.swift b/submodules/DebugSettingsUI/Sources/DebugAccountsController.swift index 0c88bf011b..28fb2cf08c 100644 --- a/submodules/DebugSettingsUI/Sources/DebugAccountsController.swift +++ b/submodules/DebugSettingsUI/Sources/DebugAccountsController.swift @@ -30,7 +30,7 @@ private enum DebugAccountsControllerSection: Int32 { } private enum DebugAccountsControllerEntry: ItemListNodeEntry { - case record(PresentationTheme, AccountRecord, Bool) + case record(PresentationTheme, AccountRecord, Bool) case loginNewAccount(PresentationTheme) var section: ItemListSectionId { @@ -87,7 +87,7 @@ private enum DebugAccountsControllerEntry: ItemListNodeEntry { } } -private func debugAccountsControllerEntries(view: AccountRecordsView, presentationData: PresentationData) -> [DebugAccountsControllerEntry] { +private func debugAccountsControllerEntries(view: AccountRecordsView, presentationData: PresentationData) -> [DebugAccountsControllerEntry] { var entries: [DebugAccountsControllerEntry] = [] for entry in view.records.sorted(by: { @@ -101,7 +101,7 @@ private func debugAccountsControllerEntries(view: AccountRecordsView, presentati return entries } -public func debugAccountsController(context: AccountContext, accountManager: AccountManager) -> ViewController { +public func debugAccountsController(context: AccountContext, accountManager: AccountManager) -> ViewController { var presentControllerImpl: ((ViewController, ViewControllerPresentationArguments?) -> Void)? let arguments = DebugAccountsControllerArguments(context: context, presentController: { controller, arguments in diff --git a/submodules/PasscodeUI/Sources/PasscodeEntryController.swift b/submodules/PasscodeUI/Sources/PasscodeEntryController.swift index 54ceb4e794..38734d0a56 100644 --- a/submodules/PasscodeUI/Sources/PasscodeEntryController.swift +++ b/submodules/PasscodeUI/Sources/PasscodeEntryController.swift @@ -4,6 +4,7 @@ import Display import AsyncDisplayKit import SwiftSignalKit import Postbox +import TelegramCore import TelegramPresentationData import TelegramUIPreferences import AccountContext @@ -37,7 +38,7 @@ public final class PasscodeEntryController: ViewController { } private let applicationBindings: TelegramApplicationBindings - private let accountManager: AccountManager + private let accountManager: AccountManager private let appLockContext: AppLockContext private let presentationDataSignal: Signal @@ -61,7 +62,7 @@ public final class PasscodeEntryController: ViewController { private var statusBarHost: StatusBarHost? private var previousStatusBarStyle: UIStatusBarStyle? - public init(applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, appLockContext: AppLockContext, presentationData: PresentationData, presentationDataSignal: Signal, statusBarHost: StatusBarHost?, challengeData: PostboxAccessChallengeData, biometrics: PasscodeEntryControllerBiometricsMode, arguments: PasscodeEntryControllerPresentationArguments) { + public init(applicationBindings: TelegramApplicationBindings, accountManager: AccountManager, appLockContext: AppLockContext, presentationData: PresentationData, presentationDataSignal: Signal, statusBarHost: StatusBarHost?, challengeData: PostboxAccessChallengeData, biometrics: PasscodeEntryControllerBiometricsMode, arguments: PasscodeEntryControllerPresentationArguments) { self.applicationBindings = applicationBindings self.accountManager = accountManager self.appLockContext = appLockContext diff --git a/submodules/PasscodeUI/Sources/PasscodeEntryControllerNode.swift b/submodules/PasscodeUI/Sources/PasscodeEntryControllerNode.swift index 429c89d459..43f382b3cc 100644 --- a/submodules/PasscodeUI/Sources/PasscodeEntryControllerNode.swift +++ b/submodules/PasscodeUI/Sources/PasscodeEntryControllerNode.swift @@ -18,7 +18,7 @@ private let subtitleFont = Font.regular(15.0) private let buttonFont = Font.regular(17.0) final class PasscodeEntryControllerNode: ASDisplayNode { - private let accountManager: AccountManager + private let accountManager: AccountManager private var presentationData: PresentationData private var theme: PresentationTheme private var strings: PresentationStrings @@ -53,7 +53,7 @@ final class PasscodeEntryControllerNode: ASDisplayNode { var checkPasscode: ((String) -> Void)? var requestBiometrics: (() -> Void)? - init(accountManager: AccountManager, presentationData: PresentationData, theme: PresentationTheme, strings: PresentationStrings, wallpaper: TelegramWallpaper, passcodeType: PasscodeEntryFieldType, biometricsType: LocalAuthBiometricAuthentication?, arguments: PasscodeEntryControllerPresentationArguments, modalPresentation: Bool) { + init(accountManager: AccountManager, presentationData: PresentationData, theme: PresentationTheme, strings: PresentationStrings, wallpaper: TelegramWallpaper, passcodeType: PasscodeEntryFieldType, biometricsType: LocalAuthBiometricAuthentication?, arguments: PasscodeEntryControllerPresentationArguments, modalPresentation: Bool) { self.accountManager = accountManager self.presentationData = presentationData self.theme = theme diff --git a/submodules/Postbox/Sources/AccountManager.swift b/submodules/Postbox/Sources/AccountManager.swift index 1025cbe4cb..eed6a75d83 100644 --- a/submodules/Postbox/Sources/AccountManager.swift +++ b/submodules/Postbox/Sources/AccountManager.swift @@ -1,15 +1,19 @@ import Foundation import SwiftSignalKit -public struct AccountManagerModifier { - public let getRecords: () -> [AccountRecord] - public let updateRecord: (AccountRecordId, (AccountRecord?) -> (AccountRecord?)) -> Void - public let getCurrent: () -> (AccountRecordId, [AccountRecordAttribute])? +public protocol AccountManagerTypes { + associatedtype Attribute: AccountRecordAttribute +} + +public struct AccountManagerModifier { + public let getRecords: () -> [AccountRecord] + public let updateRecord: (AccountRecordId, (AccountRecord?) -> (AccountRecord?)) -> Void + public let getCurrent: () -> (AccountRecordId, [Types.Attribute])? public let setCurrentId: (AccountRecordId) -> Void - public let getCurrentAuth: () -> AuthAccountRecord? - public let createAuth: ([AccountRecordAttribute]) -> AuthAccountRecord? + public let getCurrentAuth: () -> AuthAccountRecord? + public let createAuth: ([Types.Attribute]) -> AuthAccountRecord? public let removeAuth: () -> Void - public let createRecord: ([AccountRecordAttribute]) -> AccountRecordId + public let createRecord: ([Types.Attribute]) -> AccountRecordId public let getSharedData: (ValueBoxKey) -> PreferencesEntry? public let updateSharedData: (ValueBoxKey, (PreferencesEntry?) -> PreferencesEntry?) -> Void public let getAccessChallengeData: () -> PostboxAccessChallengeData @@ -21,7 +25,7 @@ public struct AccountManagerModifier { public let clearNotices: () -> Void } -final class AccountManagerImpl { +final class AccountManagerImpl { private let queue: Queue private let basePath: String private let atomicStatePath: String @@ -31,33 +35,33 @@ final class AccountManagerImpl { private var tables: [Table] = [] - private var currentAtomicState: AccountManagerAtomicState + private var currentAtomicState: AccountManagerAtomicState private var currentAtomicStateUpdated = false - private let legacyMetadataTable: AccountManagerMetadataTable - private let legacyRecordTable: AccountManagerRecordTable + private let legacyMetadataTable: AccountManagerMetadataTable + private let legacyRecordTable: AccountManagerRecordTable let sharedDataTable: AccountManagerSharedDataTable let noticeTable: NoticeTable - private var currentRecordOperations: [AccountManagerRecordOperation] = [] - private var currentMetadataOperations: [AccountManagerMetadataOperation] = [] + private var currentRecordOperations: [AccountManagerRecordOperation] = [] + private var currentMetadataOperations: [AccountManagerMetadataOperation] = [] private var currentUpdatedSharedDataKeys = Set() private var currentUpdatedNoticeEntryKeys = Set() private var currentUpdatedAccessChallengeData: PostboxAccessChallengeData? - private var recordsViews = Bag<(MutableAccountRecordsView, ValuePipe)>() + private var recordsViews = Bag<(MutableAccountRecordsView, ValuePipe>)>() - private var sharedDataViews = Bag<(MutableAccountSharedDataView, ValuePipe)>() - private var noticeEntryViews = Bag<(MutableNoticeEntryView, ValuePipe)>() + private var sharedDataViews = Bag<(MutableAccountSharedDataView, ValuePipe>)>() + private var noticeEntryViews = Bag<(MutableNoticeEntryView, ValuePipe>)>() private var accessChallengeDataViews = Bag<(MutableAccessChallengeDataView, ValuePipe)>() - static func getCurrentRecords(basePath: String) -> (records: [AccountRecord], currentId: AccountRecordId?) { + static func getCurrentRecords(basePath: String) -> (records: [AccountRecord], currentId: AccountRecordId?) { let atomicStatePath = "\(basePath)/atomic-state" do { let data = try Data(contentsOf: URL(fileURLWithPath: atomicStatePath)) - let atomicState = try JSONDecoder().decode(AccountManagerAtomicState.self, from: data) + let atomicState = try JSONDecoder().decode(AccountManagerAtomicState.self, from: data) return (atomicState.records.sorted(by: { $0.key.int64 < $1.key.int64 }).map({ $1 }), atomicState.currentRecordId) } catch let e { postboxLog("decode atomic state error: \(e)") @@ -82,15 +86,15 @@ final class AccountManagerImpl { } self.valueBox = valueBox - self.legacyMetadataTable = AccountManagerMetadataTable(valueBox: self.valueBox, table: AccountManagerMetadataTable.tableSpec(0)) - self.legacyRecordTable = AccountManagerRecordTable(valueBox: self.valueBox, table: AccountManagerRecordTable.tableSpec(1)) + self.legacyMetadataTable = AccountManagerMetadataTable(valueBox: self.valueBox, table: AccountManagerMetadataTable.tableSpec(0)) + self.legacyRecordTable = AccountManagerRecordTable(valueBox: self.valueBox, table: AccountManagerRecordTable.tableSpec(1)) self.sharedDataTable = AccountManagerSharedDataTable(valueBox: self.valueBox, table: AccountManagerSharedDataTable.tableSpec(2)) self.noticeTable = NoticeTable(valueBox: self.valueBox, table: NoticeTable.tableSpec(3)) do { let data = try Data(contentsOf: URL(fileURLWithPath: self.atomicStatePath)) do { - let atomicState = try JSONDecoder().decode(AccountManagerAtomicState.self, from: data) + let atomicState = try JSONDecoder().decode(AccountManagerAtomicState.self, from: data) self.currentAtomicState = atomicState } catch let e { postboxLog("decode atomic state error: \(e)") @@ -99,7 +103,7 @@ final class AccountManagerImpl { } } catch let e { postboxLog("load atomic state error: \(e)") - var legacyRecordDict: [AccountRecordId: AccountRecord] = [:] + var legacyRecordDict: [AccountRecordId: AccountRecord] = [:] for record in self.legacyRecordTable.getRecords() { legacyRecordDict[record.id] = record } @@ -131,12 +135,12 @@ final class AccountManagerImpl { assert(self.queue.isCurrent()) } - fileprivate func transaction(ignoreDisabled: Bool, _ f: @escaping (AccountManagerModifier) -> T) -> Signal { + fileprivate func transaction(ignoreDisabled: Bool, _ f: @escaping (AccountManagerModifier) -> T) -> Signal { return Signal { subscriber in self.queue.justDispatch { self.valueBox.begin() - let transaction = AccountManagerModifier(getRecords: { + let transaction = AccountManagerModifier(getRecords: { return self.currentAtomicState.records.map { $0.1 } }, updateRecord: { id, update in let current = self.currentAtomicState.records[id] @@ -167,7 +171,7 @@ final class AccountManagerImpl { return nil } }, createAuth: { attributes in - let record = AuthAccountRecord(id: generateAccountRecordId(), attributes: attributes) + let record = AuthAccountRecord(id: generateAccountRecordId(), attributes: attributes) self.currentAtomicState.currentAuthRecord = record self.currentAtomicStateUpdated = true self.currentMetadataOperations.append(.updateCurrentAuthAccountRecord(record)) @@ -178,7 +182,7 @@ final class AccountManagerImpl { self.currentAtomicStateUpdated = true }, createRecord: { attributes in let id = generateAccountRecordId() - let record = AccountRecord(id: id, attributes: attributes, temporarySessionId: nil) + let record = AccountRecord(id: id, attributes: attributes, temporarySessionId: nil) self.currentAtomicState.records[id] = record self.currentRecordOperations.append(.set(id: id, record: record)) self.currentAtomicStateUpdated = true @@ -282,22 +286,22 @@ final class AccountManagerImpl { } } - fileprivate func accountRecords() -> Signal { + fileprivate func accountRecords() -> Signal, NoError> { return self.transaction(ignoreDisabled: false, { transaction -> Signal in return self.accountRecordsInternal(transaction: transaction) }) |> switchToLatest } - fileprivate func sharedData(keys: Set) -> Signal { - return self.transaction(ignoreDisabled: false, { transaction -> Signal in + fileprivate func sharedData(keys: Set) -> Signal, NoError> { + return self.transaction(ignoreDisabled: false, { transaction -> Signal, NoError> in return self.sharedDataInternal(transaction: transaction, keys: keys) }) |> switchToLatest } - fileprivate func noticeEntry(key: NoticeEntryKey) -> Signal { - return self.transaction(ignoreDisabled: false, { transaction -> Signal in + fileprivate func noticeEntry(key: NoticeEntryKey) -> Signal, NoError> { + return self.transaction(ignoreDisabled: false, { transaction -> Signal, NoError> in return self.noticeEntryInternal(transaction: transaction, key: key) }) |> switchToLatest @@ -310,12 +314,12 @@ final class AccountManagerImpl { |> switchToLatest } - private func accountRecordsInternal(transaction: AccountManagerModifier) -> Signal { + private func accountRecordsInternal(transaction: AccountManagerModifier) -> Signal, NoError> { assert(self.queue.isCurrent()) - let mutableView = MutableAccountRecordsView(getRecords: { + let mutableView = MutableAccountRecordsView(getRecords: { return self.currentAtomicState.records.map { $0.1 } }, currentId: self.currentAtomicState.currentRecordId, currentAuth: self.currentAtomicState.currentAuthRecord) - let pipe = ValuePipe() + let pipe = ValuePipe>() let index = self.recordsViews.add((mutableView, pipe)) let queue = self.queue @@ -332,9 +336,9 @@ final class AccountManagerImpl { } } - private func sharedDataInternal(transaction: AccountManagerModifier, keys: Set) -> Signal { + private func sharedDataInternal(transaction: AccountManagerModifier, keys: Set) -> Signal, NoError> { let mutableView = MutableAccountSharedDataView(accountManagerImpl: self, keys: keys) - let pipe = ValuePipe() + let pipe = ValuePipe>() let index = self.sharedDataViews.add((mutableView, pipe)) let queue = self.queue @@ -351,9 +355,9 @@ final class AccountManagerImpl { } } - private func noticeEntryInternal(transaction: AccountManagerModifier, key: NoticeEntryKey) -> Signal { - let mutableView = MutableNoticeEntryView(accountManagerImpl: self, key: key) - let pipe = ValuePipe() + private func noticeEntryInternal(transaction: AccountManagerModifier, key: NoticeEntryKey) -> Signal, NoError> { + let mutableView = MutableNoticeEntryView(accountManagerImpl: self, key: key) + let pipe = ValuePipe>() let index = self.noticeEntryViews.add((mutableView, pipe)) let queue = self.queue @@ -370,7 +374,7 @@ final class AccountManagerImpl { } } - private func accessChallengeDataInternal(transaction: AccountManagerModifier) -> Signal { + private func accessChallengeDataInternal(transaction: AccountManagerModifier) -> Signal { let mutableView = MutableAccessChallengeDataView(data: transaction.getAccessChallengeData()) let pipe = ValuePipe() let index = self.accessChallengeDataViews.add((mutableView, pipe)) @@ -389,8 +393,8 @@ final class AccountManagerImpl { } } - fileprivate func currentAccountRecord(allocateIfNotExists: Bool) -> Signal<(AccountRecordId, [AccountRecordAttribute])?, NoError> { - return self.transaction(ignoreDisabled: false, { transaction -> Signal<(AccountRecordId, [AccountRecordAttribute])?, NoError> in + fileprivate func currentAccountRecord(allocateIfNotExists: Bool) -> Signal<(AccountRecordId, [Types.Attribute])?, NoError> { + return self.transaction(ignoreDisabled: false, { transaction -> Signal<(AccountRecordId, [Types.Attribute])?, NoError> in let current = transaction.getCurrent() if let _ = current { } else if allocateIfNotExists { @@ -404,7 +408,7 @@ final class AccountManagerImpl { } let signal = self.accountRecordsInternal(transaction: transaction) - |> map { view -> (AccountRecordId, [AccountRecordAttribute])? in + |> map { view -> (AccountRecordId, [Types.Attribute])? in if let currentRecord = view.currentRecord { return (currentRecord.id, currentRecord.attributes) } else { @@ -457,15 +461,15 @@ final class AccountManagerImpl { private let sharedQueue = Queue() -public final class AccountManager { +public final class AccountManager { public let basePath: String public let mediaBox: MediaBox private let queue: Queue - private let impl: QueueLocalObject + private let impl: QueueLocalObject> public let temporarySessionId: Int64 - public static func getCurrentRecords(basePath: String) -> (records: [AccountRecord], currentId: AccountRecordId?) { - return AccountManagerImpl.getCurrentRecords(basePath: basePath) + public static func getCurrentRecords(basePath: String) -> (records: [AccountRecord], currentId: AccountRecordId?) { + return AccountManagerImpl.getCurrentRecords(basePath: basePath) } public init(basePath: String, isTemporary: Bool, isReadOnly: Bool) { @@ -476,7 +480,7 @@ public final class AccountManager { self.temporarySessionId = temporarySessionId let queue = self.queue self.impl = QueueLocalObject(queue: queue, generate: { - if let value = AccountManagerImpl(queue: queue, basePath: basePath, isTemporary: isTemporary, isReadOnly: isReadOnly, temporarySessionId: temporarySessionId) { + if let value = AccountManagerImpl(queue: queue, basePath: basePath, isTemporary: isTemporary, isReadOnly: isReadOnly, temporarySessionId: temporarySessionId) { return value } else { preconditionFailure() @@ -485,7 +489,7 @@ public final class AccountManager { self.mediaBox = MediaBox(basePath: basePath + "/media") } - public func transaction(ignoreDisabled: Bool = false, _ f: @escaping (AccountManagerModifier) -> T) -> Signal { + public func transaction(ignoreDisabled: Bool = false, _ f: @escaping (AccountManagerModifier) -> T) -> Signal { return Signal { subscriber in let disposable = MetaDisposable() self.impl.with { impl in @@ -499,7 +503,7 @@ public final class AccountManager { } } - public func accountRecords() -> Signal { + public func accountRecords() -> Signal, NoError> { return Signal { subscriber in let disposable = MetaDisposable() self.impl.with { impl in @@ -513,7 +517,7 @@ public final class AccountManager { } } - public func sharedData(keys: Set) -> Signal { + public func sharedData(keys: Set) -> Signal, NoError> { return Signal { subscriber in let disposable = MetaDisposable() self.impl.with { impl in @@ -527,7 +531,7 @@ public final class AccountManager { } } - public func noticeEntry(key: NoticeEntryKey) -> Signal { + public func noticeEntry(key: NoticeEntryKey) -> Signal, NoError> { return Signal { subscriber in let disposable = MetaDisposable() self.impl.with { impl in @@ -555,7 +559,7 @@ public final class AccountManager { } } - public func currentAccountRecord(allocateIfNotExists: Bool) -> Signal<(AccountRecordId, [AccountRecordAttribute])?, NoError> { + public func currentAccountRecord(allocateIfNotExists: Bool) -> Signal<(AccountRecordId, [Types.Attribute])?, NoError> { return Signal { subscriber in let disposable = MetaDisposable() self.impl.with { impl in diff --git a/submodules/Postbox/Sources/AccountManagerAtomicState.swift b/submodules/Postbox/Sources/AccountManagerAtomicState.swift index d74557c755..360464c0d9 100644 --- a/submodules/Postbox/Sources/AccountManagerAtomicState.swift +++ b/submodules/Postbox/Sources/AccountManagerAtomicState.swift @@ -1,6 +1,6 @@ import Foundation -final class AccountManagerAtomicState: Codable { +final class AccountManagerAtomicState: Codable { enum CodingKeys: String, CodingKey { case records case currentRecordId @@ -8,12 +8,12 @@ final class AccountManagerAtomicState: Codable { case accessChallengeData } - var records: [AccountRecordId: AccountRecord] + var records: [AccountRecordId: AccountRecord] var currentRecordId: AccountRecordId? - var currentAuthRecord: AuthAccountRecord? + var currentAuthRecord: AuthAccountRecord? var accessChallengeData: PostboxAccessChallengeData - init(records: [AccountRecordId: AccountRecord] = [:], currentRecordId: AccountRecordId? = nil, currentAuthRecord: AuthAccountRecord? = nil, accessChallengeData: PostboxAccessChallengeData = .none) { + init(records: [AccountRecordId: AccountRecord] = [:], currentRecordId: AccountRecordId? = nil, currentAuthRecord: AuthAccountRecord? = nil, accessChallengeData: PostboxAccessChallengeData = .none) { self.records = records self.currentRecordId = currentRecordId self.currentAuthRecord = currentAuthRecord @@ -22,21 +22,21 @@ final class AccountManagerAtomicState: Codable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - if let records = try? container.decode(Array.self, forKey: .records) { - var recordDict: [AccountRecordId: AccountRecord] = [:] + if let records = try? container.decode(Array>.self, forKey: .records) { + var recordDict: [AccountRecordId: AccountRecord] = [:] for record in records { recordDict[record.id] = record } self.records = recordDict } else { - self.records = try container.decode(Dictionary.self, forKey: .records) + self.records = try container.decode(Dictionary>.self, forKey: .records) } if let idString = try? container.decodeIfPresent(String.self, forKey: .currentRecordId), let idValue = Int64(idString) { self.currentRecordId = AccountRecordId(rawValue: idValue) } else { self.currentRecordId = try container.decodeIfPresent(AccountRecordId.self, forKey: .currentRecordId) } - self.currentAuthRecord = try container.decodeIfPresent(AuthAccountRecord.self, forKey: .currentAuthRecord) + self.currentAuthRecord = try container.decodeIfPresent(AuthAccountRecord.self, forKey: .currentAuthRecord) if let accessChallengeData = try? container.decodeIfPresent(PostboxAccessChallengeData.self, forKey: .accessChallengeData) { self.accessChallengeData = accessChallengeData diff --git a/submodules/Postbox/Sources/AccountManagerMetadataTable.swift b/submodules/Postbox/Sources/AccountManagerMetadataTable.swift index 56407516f3..591a7fb95b 100644 --- a/submodules/Postbox/Sources/AccountManagerMetadataTable.swift +++ b/submodules/Postbox/Sources/AccountManagerMetadataTable.swift @@ -92,16 +92,16 @@ public enum PostboxAccessChallengeData: PostboxCoding, Equatable, Codable { } } -public struct AuthAccountRecord: PostboxCoding, Codable { +public struct AuthAccountRecord: Codable { enum CodingKeys: String, CodingKey { case id case attributes } public let id: AccountRecordId - public let attributes: [AccountRecordAttribute] + public let attributes: [Attribute] - init(id: AccountRecordId, attributes: [AccountRecordAttribute]) { + init(id: AccountRecordId, attributes: [Attribute]) { self.id = id self.attributes = attributes } @@ -109,41 +109,31 @@ public struct AuthAccountRecord: PostboxCoding, Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(AccountRecordId.self, forKey: .id) - let attributesData = try container.decode(Array.self, forKey: .attributes) - var attributes: [AccountRecordAttribute] = [] - for data in attributesData { - if let object = PostboxDecoder(buffer: MemoryBuffer(data: data)).decodeRootObject() as? AccountRecordAttribute { - attributes.append(object) + + if let attributesData = try? container.decode(Array.self, forKey: .attributes) { + var attributes: [Attribute] = [] + for data in attributesData { + if let attribute = try? AdaptedPostboxDecoder().decode(Attribute.self, from: data) { + attributes.append(attribute) + } } + self.attributes = attributes + } else { + let attributes = try container.decode([Attribute].self, forKey: .attributes) + self.attributes = attributes } - self.attributes = attributes } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.id, forKey: .id) - let attributesData: [Data] = self.attributes.map { attribute in - let encoder = PostboxEncoder() - encoder.encodeRootObject(attribute) - return encoder.makeData() - } - try container.encode(attributesData, forKey: .attributes) - } - - public init(decoder: PostboxDecoder) { - self.id = AccountRecordId(rawValue: decoder.decodeOptionalInt64ForKey("id")!) - self.attributes = decoder.decodeObjectArrayForKey("attributes").compactMap({ $0 as? AccountRecordAttribute }) - } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64(self.id.rawValue, forKey: "id") - encoder.encodeGenericObjectArray(self.attributes.map { $0 as PostboxCoding }, forKey: "attributes") + try container.encode(self.attributes, forKey: .attributes) } } -enum AccountManagerMetadataOperation { +enum AccountManagerMetadataOperation { case updateCurrentAccountId(AccountRecordId) - case updateCurrentAuthAccountRecord(AuthAccountRecord?) + case updateCurrentAuthAccountRecord(AuthAccountRecord?) } private enum MetadataKey: Int64 { @@ -153,7 +143,7 @@ private enum MetadataKey: Int64 { case version = 3 } -final class AccountManagerMetadataTable: Table { +final class AccountManagerMetadataTable: Table { static func tableSpec(_ id: Int32) -> ValueBoxTable { return ValueBoxTable(id: id, keyType: .int64, compactValuesOnCreation: false) } @@ -189,27 +179,26 @@ final class AccountManagerMetadataTable: Table { } } - func setCurrentAccountId(_ id: AccountRecordId, operations: inout [AccountManagerMetadataOperation]) { + func setCurrentAccountId(_ id: AccountRecordId, operations: inout [AccountManagerMetadataOperation]) { var rawValue = id.rawValue self.valueBox.set(self.table, key: self.key(.currentAccountId), value: MemoryBuffer(memory: &rawValue, capacity: 8, length: 8, freeWhenDone: false)) operations.append(.updateCurrentAccountId(id)) } - func getCurrentAuthAccount() -> AuthAccountRecord? { - if let value = self.valueBox.get(self.table, key: self.key(.currentAuthAccount)), let object = PostboxDecoder(buffer: value).decodeRootObject() as? AuthAccountRecord { + func getCurrentAuthAccount() -> AuthAccountRecord? { + if let value = self.valueBox.get(self.table, key: self.key(.currentAuthAccount)) { + let object = try? AdaptedPostboxDecoder().decode(AuthAccountRecord.self, from: value.makeData()) + return object } else { return nil } } - func setCurrentAuthAccount(_ record: AuthAccountRecord?, operations: inout [AccountManagerMetadataOperation]) { + func setCurrentAuthAccount(_ record: AuthAccountRecord?, operations: inout [AccountManagerMetadataOperation]) { if let record = record { - let encoder = PostboxEncoder() - encoder.encodeRootObject(record) - withExtendedLifetime(encoder, { - self.valueBox.set(self.table, key: self.key(.currentAuthAccount), value: encoder.readBufferNoCopy()) - }) + let data = try! AdaptedPostboxEncoder().encode(record) + self.valueBox.set(self.table, key: self.key(.currentAuthAccount), value: ReadBuffer(data: data)) } else { self.valueBox.remove(self.table, key: self.key(.currentAuthAccount), secure: false) } diff --git a/submodules/Postbox/Sources/AccountManagerRecordTable.swift b/submodules/Postbox/Sources/AccountManagerRecordTable.swift index c275d523ac..59b79ca8de 100644 --- a/submodules/Postbox/Sources/AccountManagerRecordTable.swift +++ b/submodules/Postbox/Sources/AccountManagerRecordTable.swift @@ -1,10 +1,10 @@ import Foundation -enum AccountManagerRecordOperation { - case set(id: AccountRecordId, record: AccountRecord?) +enum AccountManagerRecordOperation { + case set(id: AccountRecordId, record: AccountRecord?) } -final class AccountManagerRecordTable: Table { +final class AccountManagerRecordTable: Table { static func tableSpec(_ id: Int32) -> ValueBoxTable { return ValueBoxTable(id: id, keyType: .int64, compactValuesOnCreation: false) } @@ -15,31 +15,33 @@ final class AccountManagerRecordTable: Table { return result } - func getRecords() -> [AccountRecord] { - var records: [AccountRecord] = [] + func getRecords() -> [AccountRecord] { + var records: [AccountRecord] = [] self.valueBox.scan(self.table, values: { _, value in - let record = AccountRecord(decoder: PostboxDecoder(buffer: value)) - records.append(record) + if let record = try? AdaptedPostboxDecoder().decode(AccountRecord.self, from: value.makeData()) { + records.append(record) + } return true }) return records } - func getRecord(id: AccountRecordId) -> AccountRecord? { + func getRecord(id: AccountRecordId) -> AccountRecord? { if let value = self.valueBox.get(self.table, key: self.key(id)) { - return AccountRecord(decoder: PostboxDecoder(buffer: value)) + if let record = try? AdaptedPostboxDecoder().decode(AccountRecord.self, from: value.makeData()) { + return record + } else { + return nil + } } else { return nil } } - func setRecord(id: AccountRecordId, record: AccountRecord?, operations: inout [AccountManagerRecordOperation]) { + func setRecord(id: AccountRecordId, record: AccountRecord?, operations: inout [AccountManagerRecordOperation]) { if let record = record { - let encoder = PostboxEncoder() - record.encode(encoder) - withExtendedLifetime(encoder, { - self.valueBox.set(self.table, key: self.key(id), value: encoder.readBufferNoCopy()) - }) + let data = try! AdaptedPostboxEncoder().encode(record) + self.valueBox.set(self.table, key: self.key(id), value: ReadBuffer(data: data)) } else { self.valueBox.remove(self.table, key: self.key(id), secure: false) } diff --git a/submodules/Postbox/Sources/AccountRecord.swift b/submodules/Postbox/Sources/AccountRecord.swift index 484c28f8d9..ab8e2d3a29 100644 --- a/submodules/Postbox/Sources/AccountRecord.swift +++ b/submodules/Postbox/Sources/AccountRecord.swift @@ -1,6 +1,6 @@ import Foundation -public protocol AccountRecordAttribute: class, PostboxCoding { +public protocol AccountRecordAttribute: Codable { func isEqual(to: AccountRecordAttribute) -> Bool } @@ -15,10 +15,6 @@ public struct AccountRecordId: Comparable, Hashable, Codable { return self.rawValue } - public var hashValue: Int { - return self.rawValue.hashValue - } - public static func ==(lhs: AccountRecordId, rhs: AccountRecordId) -> Bool { return lhs.rawValue == rhs.rawValue } @@ -34,7 +30,7 @@ public func generateAccountRecordId() -> AccountRecordId { return AccountRecordId(rawValue: id) } -public final class AccountRecord: PostboxCoding, Equatable, Codable { +public final class AccountRecord: Equatable, Codable { enum CodingKeys: String, CodingKey { case id case attributes @@ -42,7 +38,7 @@ public final class AccountRecord: PostboxCoding, Equatable, Codable { } public let id: AccountRecordId - public let attributes: [AccountRecordAttribute] + public let attributes: [Attribute] public let temporarySessionId: Int64? public init(from decoder: Decoder) throws { @@ -53,17 +49,23 @@ public final class AccountRecord: PostboxCoding, Equatable, Codable { self.id = try container.decode(AccountRecordId.self, forKey: .id) } - let attributesData = try container.decode(Array.self, forKey: .attributes) - var attributes: [AccountRecordAttribute] = [] - for data in attributesData { - if let object = PostboxDecoder(buffer: MemoryBuffer(data: data)).decodeRootObject() as? AccountRecordAttribute { - attributes.append(object) + if let attributesData = try? container.decode(Array.self, forKey: .attributes) { + var attributes: [Attribute] = [] + for data in attributesData { + if let attribute = try? AdaptedPostboxDecoder().decode(Attribute.self, from: data) { + attributes.append(attribute) + } } + self.attributes = attributes + } else { + let attributes = try container.decode([Attribute].self, forKey: .attributes) + self.attributes = attributes } - self.attributes = attributes - if let temporarySessionIdString = try container.decodeIfPresent(String.self, forKey: .temporarySessionId), let temporarySessionIdValue = Int64(temporarySessionIdString) { + if let temporarySessionIdString = try? container.decodeIfPresent(String.self, forKey: .temporarySessionId), let temporarySessionIdValue = Int64(temporarySessionIdString) { self.temporarySessionId = temporarySessionIdValue + } else if let temporarySessionInt64 = try? container.decodeIfPresent(Int64.self, forKey: .temporarySessionId) { + self.temporarySessionId = temporarySessionInt64 } else { self.temporarySessionId = nil } @@ -72,39 +74,17 @@ public final class AccountRecord: PostboxCoding, Equatable, Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(String("\(self.id.rawValue)"), forKey: .id) - let attributesData: [Data] = self.attributes.map { attribute in - let encoder = PostboxEncoder() - encoder.encodeRootObject(attribute) - return encoder.makeData() - } - try container.encode(attributesData, forKey: .attributes) + try container.encode(self.attributes, forKey: .attributes) let temporarySessionIdString: String? = self.temporarySessionId.flatMap({ "\($0)" }) try container.encodeIfPresent(temporarySessionIdString, forKey: .temporarySessionId) } - public init(id: AccountRecordId, attributes: [AccountRecordAttribute], temporarySessionId: Int64?) { + public init(id: AccountRecordId, attributes: [Attribute], temporarySessionId: Int64?) { self.id = id self.attributes = attributes self.temporarySessionId = temporarySessionId } - public init(decoder: PostboxDecoder) { - self.id = AccountRecordId(rawValue: decoder.decodeInt64ForKey("id", orElse: 0)) - self.attributes = (decoder.decodeObjectArrayForKey("attributes") as [PostboxCoding]).map { $0 as! AccountRecordAttribute } - self.temporarySessionId = decoder.decodeOptionalInt64ForKey("temporarySessionId") - } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64(self.id.int64, forKey: "id") - let attributes: [PostboxCoding] = self.attributes.map { $0 } - encoder.encodeGenericObjectArray(attributes, forKey: "attributes") - if let temporarySessionId = self.temporarySessionId { - encoder.encodeInt64(temporarySessionId, forKey: "temporarySessionId") - } else { - encoder.encodeNil(forKey: "temporarySessionId") - } - } - public static func ==(lhs: AccountRecord, rhs: AccountRecord) -> Bool { if lhs.id != rhs.id { return false diff --git a/submodules/Postbox/Sources/AccountRecordsView.swift b/submodules/Postbox/Sources/AccountRecordsView.swift index 3a86acaf50..b404787231 100644 --- a/submodules/Postbox/Sources/AccountRecordsView.swift +++ b/submodules/Postbox/Sources/AccountRecordsView.swift @@ -1,17 +1,17 @@ import Foundation -final class MutableAccountRecordsView { - fileprivate var records: [AccountRecord] +final class MutableAccountRecordsView { + fileprivate var records: [AccountRecord] fileprivate var currentId: AccountRecordId? - fileprivate var currentAuth: AuthAccountRecord? + fileprivate var currentAuth: AuthAccountRecord? - init(getRecords: () -> [AccountRecord], currentId: AccountRecordId?, currentAuth: AuthAccountRecord?) { + init(getRecords: () -> [AccountRecord], currentId: AccountRecordId?, currentAuth: AuthAccountRecord?) { self.records = getRecords() self.currentId = currentId self.currentAuth = currentAuth } - func replay(operations: [AccountManagerRecordOperation], metadataOperations: [AccountManagerMetadataOperation]) -> Bool { + func replay(operations: [AccountManagerRecordOperation], metadataOperations: [AccountManagerMetadataOperation]) -> Bool { var updated = false for operation in operations { @@ -61,15 +61,15 @@ final class MutableAccountRecordsView { } } -public final class AccountRecordsView { - public let records: [AccountRecord] - public let currentRecord: AccountRecord? - public let currentAuthAccount: AuthAccountRecord? +public final class AccountRecordsView { + public let records: [AccountRecord] + public let currentRecord: AccountRecord? + public let currentAuthAccount: AuthAccountRecord? - init(_ view: MutableAccountRecordsView) { + init(_ view: MutableAccountRecordsView) { self.records = view.records if let currentId = view.currentId { - var currentRecord: AccountRecord? + var currentRecord: AccountRecord? for record in view.records { if record.id == currentId { currentRecord = record diff --git a/submodules/Postbox/Sources/AccountSharedData.swift b/submodules/Postbox/Sources/AccountSharedData.swift index eccca9a837..62676e4ffa 100644 --- a/submodules/Postbox/Sources/AccountSharedData.swift +++ b/submodules/Postbox/Sources/AccountSharedData.swift @@ -1,10 +1,10 @@ import Foundation -final class MutableAccountSharedDataView { +final class MutableAccountSharedDataView { private let keys: Set fileprivate var entries: [ValueBoxKey: PreferencesEntry] = [:] - init(accountManagerImpl: AccountManagerImpl, keys: Set) { + init(accountManagerImpl: AccountManagerImpl, keys: Set) { self.keys = keys for key in keys { if let value = accountManagerImpl.sharedDataTable.get(key: key) { @@ -13,7 +13,7 @@ final class MutableAccountSharedDataView { } } - func replay(accountManagerImpl: AccountManagerImpl, updatedKeys: Set) -> Bool { + func replay(accountManagerImpl: AccountManagerImpl, updatedKeys: Set) -> Bool { var updated = false for key in updatedKeys.intersection(self.keys) { if let value = accountManagerImpl.sharedDataTable.get(key: key) { @@ -27,10 +27,10 @@ final class MutableAccountSharedDataView { } } -public final class AccountSharedDataView { +public final class AccountSharedDataView { public let entries: [ValueBoxKey: PreferencesEntry] - init(_ view: MutableAccountSharedDataView) { + init(_ view: MutableAccountSharedDataView) { self.entries = view.entries } } diff --git a/submodules/Postbox/Sources/Coding.swift b/submodules/Postbox/Sources/Coding.swift index 33edb55996..c7437d6cb9 100644 --- a/submodules/Postbox/Sources/Coding.swift +++ b/submodules/Postbox/Sources/Coding.swift @@ -23,6 +23,12 @@ private let typeStore = { () -> EncodableTypeStore in return _typeStore }() +public func postboxEncodableTypeHash(_ type: Any.Type) -> Int32 { + let string = "\(type)" + let hash = murMurHashString32(string) + return hash +} + public func declareEncodable(_ type: Any.Type, f: @escaping(PostboxDecoder) -> PostboxCoding) { let string = "\(type)" let hash = murMurHashString32(string) @@ -232,6 +238,58 @@ enum ValueType: Int8 { case BytesArray = 13 } +enum ObjectDataValueType { + case Int32 + case Int64 + case Bool + case Double + case String + case Object(hash: Int32) + case Int32Array + case Int64Array + case ObjectArray + case ObjectDictionary + case Bytes + case Nil + case StringArray + case BytesArray +} + +private extension ObjectDataValueType { + init?(_ type: ValueType) { + switch type { + case .Int32: + self = .Int32 + case .Int64: + self = .Int64 + case .Bool: + self = .Bool + case .Double: + self = .Double + case .String: + self = .String + case .Object: + return nil + case .Int32Array: + self = .Int32Array + case .Int64Array: + self = .Int64Array + case .ObjectArray: + self = .ObjectArray + case .ObjectDictionary: + self = .ObjectDictionary + case .Bytes: + self = .Bytes + case .Nil: + self = .Nil + case .StringArray: + self = .StringArray + case .BytesArray: + self = .BytesArray + } + } +} + public final class PostboxEncoder { private let buffer = WriteBuffer() @@ -977,10 +1035,12 @@ public final class PostboxDecoder { } } - func decodeObjectDataForKey(_ key: String) -> (Data, ValueType)? { + func decodeObjectDataForKey(_ key: String) -> (Data, ObjectDataValueType)? { var actualValueType: ValueType = .Nil if PostboxDecoder.positionOnKey(self.buffer.memory, offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: nil, actualValueType: &actualValueType, consumeKey: true) { if case .Object = actualValueType { + var hash: Int32 = 0 + memcpy(&hash, self.buffer.memory + self.offset, 4) self.offset += 4 var length: Int32 = 0 @@ -990,14 +1050,14 @@ public final class PostboxDecoder { let innerData = ReadBuffer(memory: self.buffer.memory + self.offset, length: Int(length), freeWhenDone: false).makeData() self.offset += Int(length) - return (innerData, actualValueType) + return (innerData, .Object(hash: hash)) } else { let initialOffset = self.offset PostboxDecoder.skipValue(self.buffer.memory.assumingMemoryBound(to: Int8.self), offset: &self.offset, length: self.buffer.length, valueType: actualValueType) let data = ReadBuffer(memory: UnsafeMutableRawPointer(mutating: self.buffer.memory.advanced(by: initialOffset)), length: self.offset - initialOffset, freeWhenDone: false).makeData() - return (data, actualValueType) + return (data, ObjectDataValueType(actualValueType)!) } } else { return nil diff --git a/submodules/Postbox/Sources/NoticeEntryView.swift b/submodules/Postbox/Sources/NoticeEntryView.swift index fcee321560..99c5c84560 100644 --- a/submodules/Postbox/Sources/NoticeEntryView.swift +++ b/submodules/Postbox/Sources/NoticeEntryView.swift @@ -1,15 +1,15 @@ import Foundation -final class MutableNoticeEntryView { +final class MutableNoticeEntryView { private let key: NoticeEntryKey fileprivate var value: NoticeEntry? - init(accountManagerImpl: AccountManagerImpl, key: NoticeEntryKey) { + init(accountManagerImpl: AccountManagerImpl, key: NoticeEntryKey) { self.key = key self.value = accountManagerImpl.noticeTable.get(key: key) } - func replay(accountManagerImpl: AccountManagerImpl, updatedKeys: Set) -> Bool { + func replay(accountManagerImpl: AccountManagerImpl, updatedKeys: Set) -> Bool { if updatedKeys.contains(self.key) { self.value = accountManagerImpl.noticeTable.get(key: self.key) return true @@ -17,15 +17,15 @@ final class MutableNoticeEntryView { return false } - func immutableView() -> NoticeEntryView { + func immutableView() -> NoticeEntryView { return NoticeEntryView(self) } } -public final class NoticeEntryView { +public final class NoticeEntryView { public let value: NoticeEntry? - init(_ view: MutableNoticeEntryView) { + init(_ view: MutableNoticeEntryView) { self.value = view.value } } diff --git a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift index 6b83b7b0d5..23e6b1475d 100644 --- a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift +++ b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxDecoder.swift @@ -10,6 +10,16 @@ final public class AdaptedPostboxDecoder { case dataArray } + public final class RawObjectData: Codable { + public let data: Data + public let typeHash: Int32 + + public init(data: Data, typeHash: Int32) { + self.data = data + self.typeHash = typeHash + } + } + public init() { } @@ -24,7 +34,7 @@ final public class AdaptedPostboxDecoder { } extension AdaptedPostboxDecoder.ContentType { - init?(valueType: ValueType) { + init?(valueType: ObjectDataValueType) { switch valueType { case .Int32: return nil diff --git a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxKeyedDecodingContainer.swift b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxKeyedDecodingContainer.swift index 22e5e62c32..63a79a17c7 100644 --- a/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxKeyedDecodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Decoder/AdaptedPostboxKeyedDecodingContainer.swift @@ -35,6 +35,14 @@ extension _AdaptedPostboxDecoder.KeyedContainer: KeyedDecodingContainerProtocol func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { if let (data, valueType) = self.decoder.decodeObjectDataForKey(key.stringValue) { + if type == AdaptedPostboxDecoder.RawObjectData.self { + if case let .Object(typeHash) = valueType { + return AdaptedPostboxDecoder.RawObjectData(data: data, typeHash: typeHash) as! T + } else { + decodingErrorBreakpoint() + throw DecodingError.typeMismatch(T.self, DecodingError.Context(codingPath: self.codingPath + [key], debugDescription: "")) + } + } if let mappedType = AdaptedPostboxDecoder.ContentType(valueType: valueType) { return try AdaptedPostboxDecoder().decode(T.self, from: data, contentType: mappedType) } else { diff --git a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift index 014cdfdbad..9d46e3f156 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/ProxyListSettingsController.swift @@ -313,7 +313,7 @@ public func proxySettingsController(context: AccountContext, mode: ProxySettings return proxySettingsController(accountManager: context.sharedContext.accountManager, context: context, postbox: context.account.postbox, network: context.account.network, mode: mode, presentationData: presentationData, updatedPresentationData: context.sharedContext.presentationData) } -public func proxySettingsController(accountManager: AccountManager, context: AccountContext? = nil, postbox: Postbox, network: Network, mode: ProxySettingsControllerMode, presentationData: PresentationData, updatedPresentationData: Signal) -> ViewController { +public func proxySettingsController(accountManager: AccountManager, context: AccountContext? = nil, postbox: Postbox, network: Network, mode: ProxySettingsControllerMode, presentationData: PresentationData, updatedPresentationData: Signal) -> ViewController { var pushControllerImpl: ((ViewController) -> Void)? var dismissImpl: (() -> Void)? let stateValue = Atomic(value: ProxySettingsControllerState()) diff --git a/submodules/SettingsUI/Sources/Data and Storage/ProxyServerActionSheetController.swift b/submodules/SettingsUI/Sources/Data and Storage/ProxyServerActionSheetController.swift index 1b56234871..f4c1aee48b 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/ProxyServerActionSheetController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/ProxyServerActionSheetController.swift @@ -28,7 +28,7 @@ public final class ProxyServerActionSheetController: ActionSheetController { self.init(presentationData: presentationData, accountManager: context.sharedContext.accountManager, postbox: context.account.postbox, network: context.account.network, server: server, updatedPresentationData: context.sharedContext.presentationData) } - public init(presentationData: PresentationData, accountManager: AccountManager, postbox: Postbox, network: Network, server: ProxyServerSettings, updatedPresentationData: Signal?) { + public init(presentationData: PresentationData, accountManager: AccountManager, postbox: Postbox, network: Network, server: ProxyServerSettings, updatedPresentationData: Signal?) { let sheetTheme = ActionSheetControllerTheme(presentationData: presentationData) super.init(theme: sheetTheme) @@ -262,7 +262,7 @@ private final class ProxyServerInfoItemNode: ActionSheetItemNode { } private final class ProxyServerActionItem: ActionSheetItem { - private let accountManager: AccountManager + private let accountManager: AccountManager private let postbox: Postbox private let network: Network private let presentationData: PresentationData @@ -270,7 +270,7 @@ private final class ProxyServerActionItem: ActionSheetItem { private let dismiss: (Bool) -> Void private let present: (ViewController, Any?) -> Void - init(accountManager: AccountManager, postbox: Postbox, network: Network, presentationData: PresentationData, server: ProxyServerSettings, dismiss: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { + init(accountManager: AccountManager, postbox: Postbox, network: Network, presentationData: PresentationData, server: ProxyServerSettings, dismiss: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { self.accountManager = accountManager self.postbox = postbox self.network = network @@ -289,7 +289,7 @@ private final class ProxyServerActionItem: ActionSheetItem { } private final class ProxyServerActionItemNode: ActionSheetItemNode { - private let accountManager: AccountManager + private let accountManager: AccountManager private let postbox: Postbox private let network: Network private let presentationData: PresentationData @@ -305,7 +305,7 @@ private final class ProxyServerActionItemNode: ActionSheetItemNode { private let disposable = MetaDisposable() private var revertSettings: ProxySettings? - init(accountManager: AccountManager, postbox: Postbox, network: Network, presentationData: PresentationData, theme: ActionSheetControllerTheme, server: ProxyServerSettings, dismiss: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { + init(accountManager: AccountManager, postbox: Postbox, network: Network, presentationData: PresentationData, theme: ActionSheetControllerTheme, server: ProxyServerSettings, dismiss: @escaping (Bool) -> Void, present: @escaping (ViewController, Any?) -> Void) { self.accountManager = accountManager self.postbox = postbox self.network = network diff --git a/submodules/SettingsUI/Sources/Data and Storage/ProxyServerSettingsController.swift b/submodules/SettingsUI/Sources/Data and Storage/ProxyServerSettingsController.swift index 5ebc2a616f..82d43c92ef 100644 --- a/submodules/SettingsUI/Sources/Data and Storage/ProxyServerSettingsController.swift +++ b/submodules/SettingsUI/Sources/Data and Storage/ProxyServerSettingsController.swift @@ -269,7 +269,7 @@ public func proxyServerSettingsController(context: AccountContext, currentSettin return proxyServerSettingsController(context: context, presentationData: presentationData, updatedPresentationData: context.sharedContext.presentationData, accountManager: context.sharedContext.accountManager, postbox: context.account.postbox, network: context.account.network, currentSettings: currentSettings) } -func proxyServerSettingsController(context: AccountContext? = nil, presentationData: PresentationData, updatedPresentationData: Signal, accountManager: AccountManager, postbox: Postbox, network: Network, currentSettings: ProxyServerSettings?) -> ViewController { +func proxyServerSettingsController(context: AccountContext? = nil, presentationData: PresentationData, updatedPresentationData: Signal, accountManager: AccountManager, postbox: Postbox, network: Network, currentSettings: ProxyServerSettings?) -> ViewController { var currentMode: ProxyServerSettingsControllerMode = .socks5 var currentUsername: String? var currentPassword: String? diff --git a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift index 67753fd72e..b1be092676 100644 --- a/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift +++ b/submodules/TelegramCallsUI/Sources/PresentationCallManager.swift @@ -49,7 +49,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { private let isMediaPlaying: () -> Bool private let resumeMediaPlayback: () -> Void - private let accountManager: AccountManager + private let accountManager: AccountManager private let audioSession: ManagedAudioSession private let callKitIntegration: CallKitIntegration? @@ -113,7 +113,7 @@ public final class PresentationCallManagerImpl: PresentationCallManager { return OngoingCallContext.versions(includeExperimental: includeExperimental, includeReference: includeReference) } - public init(accountManager: AccountManager, getDeviceAccessData: @escaping () -> (presentationData: PresentationData, present: (ViewController, Any?) -> Void, openSettings: () -> Void), isMediaPlaying: @escaping () -> Bool, resumeMediaPlayback: @escaping () -> Void, audioSession: ManagedAudioSession, activeAccounts: Signal<[AccountContext], NoError>) { + public init(accountManager: AccountManager, getDeviceAccessData: @escaping () -> (presentationData: PresentationData, present: (ViewController, Any?) -> Void, openSettings: () -> Void), isMediaPlaying: @escaping () -> Bool, resumeMediaPlayback: @escaping () -> Void, audioSession: ManagedAudioSession, activeAccounts: Signal<[AccountContext], NoError>) { self.getDeviceAccessData = getDeviceAccessData self.accountManager = accountManager self.audioSession = audioSession diff --git a/submodules/TelegramCore/Sources/Account/Account.swift b/submodules/TelegramCore/Sources/Account/Account.swift index 042a065381..d3f7e8f9f7 100644 --- a/submodules/TelegramCore/Sources/Account/Account.swift +++ b/submodules/TelegramCore/Sources/Account/Account.swift @@ -120,7 +120,7 @@ public class UnauthorizedAccount { self.stateManager.reset() } - public func changedMasterDatacenterId(accountManager: AccountManager, masterDatacenterId: Int32) -> Signal { + public func changedMasterDatacenterId(accountManager: AccountManager, masterDatacenterId: Int32) -> Signal { if masterDatacenterId == Int32(self.network.mtProto.datacenterId) { return .single(self) } else { @@ -235,7 +235,7 @@ public func accountLegacyAccessChallengeData(rootPath: String, id: AccountRecord } } -public func accountWithId(accountManager: AccountManager, networkArguments: NetworkInitializationArguments, id: AccountRecordId, encryptionParameters: ValueBoxEncryptionParameters, supplementary: Bool, rootPath: String, beginWithTestingEnvironment: Bool, backupData: AccountBackupData?, auxiliaryMethods: AccountAuxiliaryMethods, shouldKeepAutoConnection: Bool = true) -> Signal { +public func accountWithId(accountManager: AccountManager, networkArguments: NetworkInitializationArguments, id: AccountRecordId, encryptionParameters: ValueBoxEncryptionParameters, supplementary: Bool, rootPath: String, beginWithTestingEnvironment: Bool, backupData: AccountBackupData?, auxiliaryMethods: AccountAuxiliaryMethods, shouldKeepAutoConnection: Bool = true) -> Signal { let path = "\(rootPath)/\(accountRecordIdPathName(id))" let postbox = openPostbox(basePath: path + "/postbox", seedConfiguration: telegramPostboxSeedConfiguration, encryptionParameters: encryptionParameters, timestampForAbsoluteTimeBasedOperations: Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970), isTemporary: false, isReadOnly: false, useCopy: false) @@ -258,7 +258,7 @@ public func accountWithId(accountManager: AccountManager, networkArguments: Netw let backupState = AuthorizedAccountState(isTestingEnvironment: beginWithTestingEnvironment, masterDatacenterId: backupData.masterDatacenterId, peerId: PeerId(backupData.peerId), state: nil) state = backupState let dict = NSMutableDictionary() - dict.setObject(MTDatacenterAuthInfo(authKey: backupData.masterDatacenterKey, authKeyId: backupData.masterDatacenterKeyId, saltSet: [], authKeyAttributes: [:]), forKey: backupData.masterDatacenterId as NSNumber) + dict.setObject(MTDatacenterAuthInfo(authKey: backupData.masterDatacenterKey, authKeyId: backupData.masterDatacenterKeyId, saltSet: [], authKeyAttributes: [:])!, forKey: backupData.masterDatacenterId as NSNumber) let data = NSKeyedArchiver.archivedData(withRootObject: dict) transaction.setState(backupState) transaction.setKeychainEntry(data, forKey: "persistent:datacenterAuthInfoById") @@ -902,7 +902,7 @@ public class Account { private var lastSmallLogPostTimestamp: Double? private let smallLogPostDisposable = MetaDisposable() - public init(accountManager: AccountManager, id: AccountRecordId, basePath: String, testingEnvironment: Bool, postbox: Postbox, network: Network, networkArguments: NetworkInitializationArguments, peerId: PeerId, auxiliaryMethods: AccountAuxiliaryMethods, supplementary: Bool) { + public init(accountManager: AccountManager, id: AccountRecordId, basePath: String, testingEnvironment: Bool, postbox: Postbox, network: Network, networkArguments: NetworkInitializationArguments, peerId: PeerId, auxiliaryMethods: AccountAuxiliaryMethods, supplementary: Bool) { self.id = id self.basePath = basePath self.testingEnvironment = testingEnvironment diff --git a/submodules/TelegramCore/Sources/Account/AccountManager.swift b/submodules/TelegramCore/Sources/Account/AccountManager.swift index ceb438a8bb..418f4d0809 100644 --- a/submodules/TelegramCore/Sources/Account/AccountManager.swift +++ b/submodules/TelegramCore/Sources/Account/AccountManager.swift @@ -4,14 +4,77 @@ import SwiftSignalKit import TelegramApi import MtProtoKit - private enum AccountKind { case authorized case unauthorized } +public enum TelegramAccountRecordAttribute: AccountRecordAttribute, Equatable { + enum CodingKeys: String, CodingKey { + case backupData + case environment + case sortOrder + case loggedOut + case legacyRootObject = "_" + } + + case backupData(AccountBackupDataAttribute) + case environment(AccountEnvironmentAttribute) + case sortOrder(AccountSortOrderAttribute) + case loggedOut(LoggedOutAccountAttribute) + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + if let backupData = try? container.decodeIfPresent(AccountBackupDataAttribute.self, forKey: .backupData) { + self = .backupData(backupData) + } else if let environment = try? container.decodeIfPresent(AccountEnvironmentAttribute.self, forKey: .environment) { + self = .environment(environment) + } else if let sortOrder = try? container.decodeIfPresent(AccountSortOrderAttribute.self, forKey: .sortOrder) { + self = .sortOrder(sortOrder) + } else if let loggedOut = try? container.decodeIfPresent(LoggedOutAccountAttribute.self, forKey: .loggedOut) { + self = .loggedOut(loggedOut) + } else { + let legacyRootObjectData = try! container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: .legacyRootObject) + if legacyRootObjectData.typeHash == postboxEncodableTypeHash(AccountBackupDataAttribute.self) { + self = .backupData(try! AdaptedPostboxDecoder().decode(AccountBackupDataAttribute.self, from: legacyRootObjectData.data)) + } else if legacyRootObjectData.typeHash == postboxEncodableTypeHash(AccountEnvironmentAttribute.self) { + self = .environment(try! AdaptedPostboxDecoder().decode(AccountEnvironmentAttribute.self, from: legacyRootObjectData.data)) + } else if legacyRootObjectData.typeHash == postboxEncodableTypeHash(AccountSortOrderAttribute.self) { + self = .sortOrder(try! AdaptedPostboxDecoder().decode(AccountSortOrderAttribute.self, from: legacyRootObjectData.data)) + } else if legacyRootObjectData.typeHash == postboxEncodableTypeHash(LoggedOutAccountAttribute.self) { + self = .loggedOut(try! AdaptedPostboxDecoder().decode(LoggedOutAccountAttribute.self, from: legacyRootObjectData.data)) + } else { + preconditionFailure() + } + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + switch self { + case let .backupData(backupData): + try container.encode(backupData, forKey: .backupData) + case let .environment(environment): + try container.encode(environment, forKey: .environment) + case let .sortOrder(sortOrder): + try container.encode(sortOrder, forKey: .sortOrder) + case let .loggedOut(loggedOut): + try container.encode(loggedOut, forKey: .loggedOut) + } + } + + public func isEqual(to: AccountRecordAttribute) -> Bool { + return self == to as? TelegramAccountRecordAttribute + } +} + +public final class TelegramAccountManagerTypes: AccountManagerTypes { + public typealias Attribute = TelegramAccountRecordAttribute +} + private var declaredEncodables: Void = { - declareEncodable(AuthAccountRecord.self, f: { AuthAccountRecord(decoder: $0) }) declareEncodable(UnauthorizedAccountState.self, f: { UnauthorizedAccountState(decoder: $0) }) declareEncodable(AuthorizedAccountState.self, f: { AuthorizedAccountState(decoder: $0) }) declareEncodable(TelegramUser.self, f: { TelegramUser(decoder: $0) }) @@ -74,9 +137,6 @@ private var declaredEncodables: Void = { declareEncodable(RecentMediaItem.self, f: { RecentMediaItem(decoder: $0) }) declareEncodable(RecentPeerItem.self, f: { RecentPeerItem(decoder: $0) }) declareEncodable(RecentHashtagItem.self, f: { RecentHashtagItem(decoder: $0) }) - declareEncodable(LoggedOutAccountAttribute.self, f: { LoggedOutAccountAttribute(decoder: $0) }) - declareEncodable(AccountEnvironmentAttribute.self, f: { AccountEnvironmentAttribute(decoder: $0) }) - declareEncodable(AccountSortOrderAttribute.self, f: { AccountSortOrderAttribute(decoder: $0) }) declareEncodable(CloudChatClearHistoryOperation.self, f: { CloudChatClearHistoryOperation(decoder: $0) }) declareEncodable(OutgoingContentInfoMessageAttribute.self, f: { OutgoingContentInfoMessageAttribute(decoder: $0) }) declareEncodable(ConsumableContentMessageAttribute.self, f: { ConsumableContentMessageAttribute(decoder: $0) }) @@ -143,7 +203,6 @@ private var declaredEncodables: Void = { declareEncodable(CloudDocumentSizeMediaResource.self, f: { CloudDocumentSizeMediaResource(decoder: $0) }) declareEncodable(CloudPeerPhotoSizeMediaResource.self, f: { CloudPeerPhotoSizeMediaResource(decoder: $0) }) declareEncodable(CloudStickerPackThumbnailMediaResource.self, f: { CloudStickerPackThumbnailMediaResource(decoder: $0) }) - declareEncodable(AccountBackupDataAttribute.self, f: { AccountBackupDataAttribute(decoder: $0) }) declareEncodable(ContentRequiresValidationMessageAttribute.self, f: { ContentRequiresValidationMessageAttribute(decoder: $0) }) declareEncodable(WasScheduledMessageAttribute.self, f: { WasScheduledMessageAttribute(decoder: $0) }) declareEncodable(OutgoingScheduleInfoMessageAttribute.self, f: { OutgoingScheduleInfoMessageAttribute(decoder: $0) }) @@ -232,7 +291,7 @@ public final class TemporaryAccount { } } -public func temporaryAccount(manager: AccountManager, rootPath: String, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { +public func temporaryAccount(manager: AccountManager, rootPath: String, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { return manager.allocatedTemporaryAccountId() |> mapToSignal { id -> Signal in let path = "\(rootPath)/\(accountRecordIdPathName(id))" @@ -250,7 +309,7 @@ public func temporaryAccount(manager: AccountManager, rootPath: String, encrypti } } -public func currentAccount(allocateIfNotExists: Bool, networkArguments: NetworkInitializationArguments, supplementary: Bool, manager: AccountManager, rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { +public func currentAccount(allocateIfNotExists: Bool, networkArguments: NetworkInitializationArguments, supplementary: Bool, manager: AccountManager, rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { return manager.currentAccountRecord(allocateIfNotExists: allocateIfNotExists) |> distinctUntilChanged(isEqual: { lhs, rhs in return lhs?.0 == rhs?.0 @@ -261,7 +320,7 @@ public func currentAccount(allocateIfNotExists: Bool, networkArguments: NetworkI return reload.get() |> mapToSignal { _ -> Signal in let beginWithTestingEnvironment = record.1.contains(where: { attribute in - if let attribute = attribute as? AccountEnvironmentAttribute, case .test = attribute.environment { + if case let .environment(environment) = attribute, case .test = environment.environment { return true } else { return false @@ -314,7 +373,7 @@ public func currentAccount(allocateIfNotExists: Bool, networkArguments: NetworkI } } -public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManager, alreadyLoggedOutRemotely: Bool) -> Signal { +public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManager, alreadyLoggedOutRemotely: Bool) -> Signal { Logger.shared.log("AccountManager", "logoutFromAccount \(id)") return accountManager.transaction { transaction -> Void in transaction.updateRecord(id, { current in @@ -323,7 +382,7 @@ public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManage } else if let current = current { var found = false for attribute in current.attributes { - if attribute is LoggedOutAccountAttribute { + if case .loggedOut = attribute { found = true break } @@ -331,7 +390,7 @@ public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManage if found { return current } else { - return AccountRecord(id: current.id, attributes: current.attributes + [LoggedOutAccountAttribute()], temporarySessionId: nil) + return AccountRecord(id: current.id, attributes: current.attributes + [.loggedOut(LoggedOutAccountAttribute())], temporarySessionId: nil) } } else { return nil @@ -340,7 +399,7 @@ public func logoutFromAccount(id: AccountRecordId, accountManager: AccountManage } } -public func managedCleanupAccounts(networkArguments: NetworkInitializationArguments, accountManager: AccountManager, rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { +public func managedCleanupAccounts(networkArguments: NetworkInitializationArguments, accountManager: AccountManager, rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { let currentTemporarySessionId = accountManager.temporarySessionId return Signal { subscriber in let loggedOutAccounts = Atomic<[AccountRecordId: MetaDisposable]>(value: [:]) @@ -355,12 +414,12 @@ public func managedCleanupAccounts(networkArguments: NetworkInitializationArgume }).start() let disposable = accountManager.accountRecords().start(next: { view in var disposeList: [(AccountRecordId, MetaDisposable)] = [] - var beginList: [(AccountRecordId, [AccountRecordAttribute], MetaDisposable)] = [] + var beginList: [(AccountRecordId, [TelegramAccountManagerTypes.Attribute], MetaDisposable)] = [] let _ = loggedOutAccounts.modify { disposables in - var validIds: [AccountRecordId: [AccountRecordAttribute]] = [:] + var validIds: [AccountRecordId: [TelegramAccountManagerTypes.Attribute]] = [:] outer: for record in view.records { for attribute in record.attributes { - if attribute is LoggedOutAccountAttribute { + if case .loggedOut = attribute { validIds[record.id] = record.attributes continue outer } @@ -425,9 +484,9 @@ public func managedCleanupAccounts(networkArguments: NetworkInitializationArgume } } -private func cleanupAccount(networkArguments: NetworkInitializationArguments, accountManager: AccountManager, id: AccountRecordId, encryptionParameters: ValueBoxEncryptionParameters, attributes: [AccountRecordAttribute], rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods) -> Signal { +private func cleanupAccount(networkArguments: NetworkInitializationArguments, accountManager: AccountManager, id: AccountRecordId, encryptionParameters: ValueBoxEncryptionParameters, attributes: [TelegramAccountManagerTypes.Attribute], rootPath: String, auxiliaryMethods: AccountAuxiliaryMethods) -> Signal { let beginWithTestingEnvironment = attributes.contains(where: { attribute in - if let attribute = attribute as? AccountEnvironmentAttribute, case .test = attribute.environment { + if case let .environment(accountEnvironment) = attribute, case .test = accountEnvironment.environment { return true } else { return false diff --git a/submodules/TelegramCore/Sources/Authorization.swift b/submodules/TelegramCore/Sources/Authorization.swift index 9845a8d692..17dde9f772 100644 --- a/submodules/TelegramCore/Sources/Authorization.swift +++ b/submodules/TelegramCore/Sources/Authorization.swift @@ -14,17 +14,20 @@ public enum AuthorizationCodeRequestError { case timeout } -func switchToAuthorizedAccount(transaction: AccountManagerModifier, account: UnauthorizedAccount) { +func switchToAuthorizedAccount(transaction: AccountManagerModifier, account: UnauthorizedAccount) { let nextSortOrder = (transaction.getRecords().map({ record -> Int32 in for attribute in record.attributes { - if let attribute = attribute as? AccountSortOrderAttribute { - return attribute.order + if case let .sortOrder(sortOrder) = attribute { + return sortOrder.order } } return 0 }).max() ?? 0) + 1 transaction.updateRecord(account.id, { _ in - return AccountRecord(id: account.id, attributes: [AccountEnvironmentAttribute(environment: account.testingEnvironment ? .test : .production), AccountSortOrderAttribute(order: nextSortOrder)], temporarySessionId: nil) + return AccountRecord(id: account.id, attributes: [ + .environment(AccountEnvironmentAttribute(environment: account.testingEnvironment ? .test : .production)), + .sortOrder(AccountSortOrderAttribute(order: nextSortOrder)) + ], temporarySessionId: nil) }) transaction.setCurrentId(account.id) transaction.removeAuth() @@ -68,7 +71,7 @@ private func ~=(pattern: Regex, matchable: T) -> return matchable.match(pattern) } -public func sendAuthorizationCode(accountManager: AccountManager, account: UnauthorizedAccount, phoneNumber: String, apiId: Int32, apiHash: String, syncContacts: Bool) -> Signal { +public func sendAuthorizationCode(accountManager: AccountManager, account: UnauthorizedAccount, phoneNumber: String, apiId: Int32, apiHash: String, syncContacts: Bool) -> Signal { let sendCode = Api.functions.auth.sendCode(phoneNumber: phoneNumber, apiId: apiId, apiHash: apiHash, settings: .codeSettings(flags: 0)) let codeAndAccount = account.network.request(sendCode, automaticFloodWait: false) @@ -202,7 +205,7 @@ public enum AuthorizeWithCodeResult { case loggedIn } -public func authorizeWithCode(accountManager: AccountManager, account: UnauthorizedAccount, code: String, termsOfService: UnauthorizedAccountTermsOfService?) -> Signal { +public func authorizeWithCode(accountManager: AccountManager, account: UnauthorizedAccount, code: String, termsOfService: UnauthorizedAccountTermsOfService?) -> Signal { return account.postbox.transaction { transaction -> Signal in if let state = transaction.getState() as? UnauthorizedAccountState { switch state.contents { @@ -295,7 +298,7 @@ public enum AuthorizationPasswordVerificationError { case generic } -public func authorizeWithPassword(accountManager: AccountManager, account: UnauthorizedAccount, password: String, syncContacts: Bool) -> Signal { +public func authorizeWithPassword(accountManager: AccountManager, account: UnauthorizedAccount, password: String, syncContacts: Bool) -> Signal { return verifyPassword(account, password: password) |> `catch` { error -> Signal in if error.errorDescription.hasPrefix("FLOOD_WAIT") { @@ -372,7 +375,7 @@ public final class RecoveredAccountData { } } -public func loginWithRecoveredAccountData(accountManager: AccountManager, account: UnauthorizedAccount, recoveredAccountData: RecoveredAccountData, syncContacts: Bool) -> Signal { +public func loginWithRecoveredAccountData(accountManager: AccountManager, account: UnauthorizedAccount, recoveredAccountData: RecoveredAccountData, syncContacts: Bool) -> Signal { return account.postbox.transaction { transaction -> Signal in switch recoveredAccountData.authorization { case let .authorization(_, _, user): @@ -492,7 +495,7 @@ public enum SignUpError { case invalidLastName } -public func signUpWithName(accountManager: AccountManager, account: UnauthorizedAccount, firstName: String, lastName: String, avatarData: Data?, avatarVideo: Signal?, videoStartTimestamp: Double?) -> Signal { +public func signUpWithName(accountManager: AccountManager, account: UnauthorizedAccount, firstName: String, lastName: String, avatarData: Data?, avatarVideo: Signal?, videoStartTimestamp: Double?) -> Signal { return account.postbox.transaction { transaction -> Signal in if let state = transaction.getState() as? UnauthorizedAccountState, case let .signUp(number, codeHash, _, _, _, syncContacts) = state.contents { return account.network.request(Api.functions.auth.signUp(phoneNumber: number, phoneCodeHash: codeHash, firstName: firstName, lastName: lastName)) @@ -525,8 +528,8 @@ public func signUpWithName(accountManager: AccountManager, account: Unauthorized let switchedAccounts = accountManager.transaction { transaction -> Void in switchToAuthorizedAccount(transaction: transaction, account: account) - } - |> castError(SignUpError.self) + } + |> castError(SignUpError.self) if let avatarData = avatarData { let resource = LocalFileMediaResource(fileId: Int64.random(in: Int64.min ... Int64.max)) diff --git a/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift b/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift index 513a055822..9d10248914 100644 --- a/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/AutodownloadSettings.swift @@ -4,7 +4,7 @@ import TelegramApi import SwiftSignalKit -public func updateAutodownloadSettingsInteractively(accountManager: AccountManager, _ f: @escaping (AutodownloadSettings) -> AutodownloadSettings) -> Signal { +public func updateAutodownloadSettingsInteractively(accountManager: AccountManager, _ f: @escaping (AutodownloadSettings) -> AutodownloadSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(SharedDataKeys.autodownloadSettings, { entry in let currentSettings: AutodownloadSettings diff --git a/submodules/TelegramCore/Sources/Settings/CacheStorageSettings.swift b/submodules/TelegramCore/Sources/Settings/CacheStorageSettings.swift index 6eaa896346..271caf26f6 100644 --- a/submodules/TelegramCore/Sources/Settings/CacheStorageSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/CacheStorageSettings.swift @@ -3,7 +3,7 @@ import Postbox import SwiftSignalKit -public func updateCacheStorageSettingsInteractively(accountManager: AccountManager, _ f: @escaping (CacheStorageSettings) -> CacheStorageSettings) -> Signal { +public func updateCacheStorageSettingsInteractively(accountManager: AccountManager, _ f: @escaping (CacheStorageSettings) -> CacheStorageSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(SharedDataKeys.cacheStorageSettings, { entry in let currentSettings: CacheStorageSettings diff --git a/submodules/TelegramCore/Sources/Settings/LoggingSettings.swift b/submodules/TelegramCore/Sources/Settings/LoggingSettings.swift index 40865e6458..f6e240824e 100644 --- a/submodules/TelegramCore/Sources/Settings/LoggingSettings.swift +++ b/submodules/TelegramCore/Sources/Settings/LoggingSettings.swift @@ -3,7 +3,7 @@ import Postbox import SwiftSignalKit import MtProtoKit -public func updateLoggingSettings(accountManager: AccountManager, _ f: @escaping (LoggingSettings) -> LoggingSettings) -> Signal { +public func updateLoggingSettings(accountManager: AccountManager, _ f: @escaping (LoggingSettings) -> LoggingSettings) -> Signal { return accountManager.transaction { transaction -> Void in var updated: LoggingSettings? transaction.updateSharedData(SharedDataKeys.loggingSettings, { current in diff --git a/submodules/TelegramCore/Sources/Settings/ProxySettings.swift b/submodules/TelegramCore/Sources/Settings/ProxySettings.swift index 4f15b8df39..4316c1206a 100644 --- a/submodules/TelegramCore/Sources/Settings/ProxySettings.swift +++ b/submodules/TelegramCore/Sources/Settings/ProxySettings.swift @@ -3,7 +3,7 @@ import Postbox import SwiftSignalKit import MtProtoKit -public func updateProxySettingsInteractively(accountManager: AccountManager, _ f: @escaping (ProxySettings) -> ProxySettings) -> Signal { +public func updateProxySettingsInteractively(accountManager: AccountManager, _ f: @escaping (ProxySettings) -> ProxySettings) -> Signal { return accountManager.transaction { transaction -> Bool in return updateProxySettingsInteractively(transaction: transaction, f) } @@ -20,7 +20,7 @@ extension ProxyServerSettings { } } -public func updateProxySettingsInteractively(transaction: AccountManagerModifier, _ f: @escaping (ProxySettings) -> ProxySettings) -> Bool { +public func updateProxySettingsInteractively(transaction: AccountManagerModifier, _ f: @escaping (ProxySettings) -> ProxySettings) -> Bool { var hasChanges = false transaction.updateSharedData(SharedDataKeys.proxySettings, { current in let previous = (current as? ProxySettings) ?? ProxySettings.defaultSettings diff --git a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift index fa457495d4..b65823fdf5 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManagementUtils.swift @@ -2255,7 +2255,7 @@ private func recordPeerActivityTimestamp(peerId: PeerId, timestamp: Int32, into } } -func replayFinalState(accountManager: AccountManager, postbox: Postbox, accountPeerId: PeerId, mediaBox: MediaBox, encryptionProvider: EncryptionProvider, transaction: Transaction, auxiliaryMethods: AccountAuxiliaryMethods, finalState: AccountFinalState, removePossiblyDeliveredMessagesUniqueIds: [Int64: PeerId]) -> AccountReplayedFinalState? { +func replayFinalState(accountManager: AccountManager, postbox: Postbox, accountPeerId: PeerId, mediaBox: MediaBox, encryptionProvider: EncryptionProvider, transaction: Transaction, auxiliaryMethods: AccountAuxiliaryMethods, finalState: AccountFinalState, removePossiblyDeliveredMessagesUniqueIds: [Int64: PeerId]) -> AccountReplayedFinalState? { let verified = verifyTransaction(transaction, finalState: finalState.state) if !verified { Logger.shared.log("State", "failed to verify final state") diff --git a/submodules/TelegramCore/Sources/State/AccountStateManager.swift b/submodules/TelegramCore/Sources/State/AccountStateManager.swift index f619487341..b1416aad0f 100644 --- a/submodules/TelegramCore/Sources/State/AccountStateManager.swift +++ b/submodules/TelegramCore/Sources/State/AccountStateManager.swift @@ -53,7 +53,7 @@ public enum DeletedMessageId: Hashable { public final class AccountStateManager { private let queue = Queue() private let accountPeerId: PeerId - private let accountManager: AccountManager + private let accountManager: AccountManager private let postbox: Postbox private let network: Network private let callSessionManager: CallSessionManager @@ -166,7 +166,7 @@ public final class AccountStateManager { private let appliedQtsPromise = Promise(nil) private let appliedQtsDisposable = MetaDisposable() - init(accountPeerId: PeerId, accountManager: AccountManager, postbox: Postbox, network: Network, callSessionManager: CallSessionManager, addIsContactUpdates: @escaping ([(PeerId, Bool)]) -> Void, shouldKeepOnlinePresence: Signal, peerInputActivityManager: PeerInputActivityManager, auxiliaryMethods: AccountAuxiliaryMethods) { + init(accountPeerId: PeerId, accountManager: AccountManager, postbox: Postbox, network: Network, callSessionManager: CallSessionManager, addIsContactUpdates: @escaping ([(PeerId, Bool)]) -> Void, shouldKeepOnlinePresence: Signal, peerInputActivityManager: PeerInputActivityManager, auxiliaryMethods: AccountAuxiliaryMethods) { self.accountPeerId = accountPeerId self.accountManager = accountManager self.postbox = postbox diff --git a/submodules/TelegramCore/Sources/State/ManagedAutodownloadSettingsUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedAutodownloadSettingsUpdates.swift index 4de3ecf5d3..ab86a5bd7b 100644 --- a/submodules/TelegramCore/Sources/State/ManagedAutodownloadSettingsUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedAutodownloadSettingsUpdates.swift @@ -5,7 +5,7 @@ import TelegramApi import MtProtoKit -func managedAutodownloadSettingsUpdates(accountManager: AccountManager, network: Network) -> Signal { +func managedAutodownloadSettingsUpdates(accountManager: AccountManager, network: Network) -> Signal { let poll = Signal { subscriber in return (network.request(Api.functions.account.getAutoDownloadSettings()) |> retryRequest diff --git a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift index 3ed8038358..2453192284 100644 --- a/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift +++ b/submodules/TelegramCore/Sources/State/ManagedConfigurationUpdates.swift @@ -5,7 +5,7 @@ import TelegramApi import MtProtoKit -func managedConfigurationUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { +func managedConfigurationUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { let poll = Signal { subscriber in return (network.request(Api.functions.help.getConfig()) |> retryRequest diff --git a/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift b/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift index fa6f69621d..182f8787a3 100644 --- a/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift +++ b/submodules/TelegramCore/Sources/State/ManagedLocalizationUpdatesOperations.swift @@ -65,7 +65,7 @@ private func withTakenOperation(postbox: Postbox, peerId: PeerId, tag: PeerOpera } |> switchToLatest } -func managedLocalizationUpdatesOperations(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { +func managedLocalizationUpdatesOperations(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { return Signal { _ in let tag: PeerOperationLogTag = OperationLogTags.SynchronizeLocalizationUpdates @@ -116,7 +116,7 @@ private enum SynchronizeLocalizationUpdatesError { case reset } -func getLocalization(_ transaction: AccountManagerModifier) -> (primary: (code: String, version: Int32, entries: [LocalizationEntry]), secondary: (code: String, version: Int32, entries: [LocalizationEntry])?) { +func getLocalization(_ transaction: AccountManagerModifier) -> (primary: (code: String, version: Int32, entries: [LocalizationEntry]), secondary: (code: String, version: Int32, entries: [LocalizationEntry])?) { let localizationSettings: LocalizationSettings? if let current = transaction.getSharedData(SharedDataKeys.localizationSettings) as? LocalizationSettings { localizationSettings = current @@ -148,7 +148,7 @@ private func parseLangPackDifference(_ difference: Api.LangPackDifference) -> (c } } -private func synchronizeLocalizationUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { +private func synchronizeLocalizationUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { let currentLanguageAndVersion = accountManager.transaction { transaction -> (primary: (code: String, version: Int32), secondary: (code: String, version: Int32)?) in let (primary, secondary) = getLocalization(transaction) return ((primary.code, primary.version), secondary.flatMap({ ($0.code, $0.version) })) @@ -240,7 +240,7 @@ private func synchronizeLocalizationUpdates(accountManager: AccountManager, post } } -func tryApplyingLanguageDifference(transaction: AccountManagerModifier, langCode: String, difference: Api.LangPackDifference) -> Bool { +func tryApplyingLanguageDifference(transaction: AccountManagerModifier, langCode: String, difference: Api.LangPackDifference) -> Bool { let (primary, secondary) = getLocalization(transaction) switch difference { case let .langPackDifference(updatedCode, fromVersion, updatedVersion, strings): diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountBackupDataAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountBackupDataAttribute.swift index e2c90facfa..d5fcbd4c51 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountBackupDataAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountBackupDataAttribute.swift @@ -15,32 +15,34 @@ public struct AccountBackupData: Codable, Equatable { } } -public final class AccountBackupDataAttribute: AccountRecordAttribute, Equatable { +public final class AccountBackupDataAttribute: Codable, Equatable { + enum CodingKeys: String, CodingKey { + case data + } + public let data: AccountBackupData? public init(data: AccountBackupData?) { self.data = data } - - public init(decoder: PostboxDecoder) { - self.data = try? JSONDecoder().decode(AccountBackupData.self, from: decoder.decodeDataForKey("data") ?? Data()) + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.data = try? JSONDecoder().decode(AccountBackupData.self, from: (try? container.decode(Data.self, forKey: .data)) ?? Data()) } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if let data = self.data, let serializedData = try? JSONEncoder().encode(data) { - encoder.encodeData(serializedData, forKey: "data") + try container.encode(serializedData, forKey: .data) + } else { + try container.encodeNil(forKey: .data) } } public static func ==(lhs: AccountBackupDataAttribute, rhs: AccountBackupDataAttribute) -> Bool { return lhs.data == rhs.data } - - public func isEqual(to: AccountRecordAttribute) -> Bool { - if let to = to as? AccountBackupDataAttribute { - return self == to - } else { - return false - } - } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountEnvironmentAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountEnvironmentAttribute.swift index dda33baa2f..3355aa0291 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountEnvironmentAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountEnvironmentAttribute.swift @@ -6,26 +6,33 @@ public enum AccountEnvironment: Int32 { case test = 1 } -public final class AccountEnvironmentAttribute: AccountRecordAttribute { +public final class AccountEnvironmentAttribute: Codable, Equatable { + enum CodingKeys: String, CodingKey { + case environment + } + public let environment: AccountEnvironment public init(environment: AccountEnvironment) { self.environment = environment } - public init(decoder: PostboxDecoder) { - self.environment = AccountEnvironment(rawValue: decoder.decodeInt32ForKey("environment", orElse: 0)) ?? .production + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let environmentValue: Int32 = (try? container.decode(Int32.self, forKey: .environment)) ?? 0 + + self.environment = AccountEnvironment(rawValue: environmentValue) ?? .production } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.environment.rawValue, forKey: "environment") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.environment.rawValue, forKey: .environment) } - - public func isEqual(to: AccountRecordAttribute) -> Bool { - guard let to = to as? AccountEnvironmentAttribute else { - return false - } - if self.environment != to.environment { + + public static func ==(lhs: AccountEnvironmentAttribute, rhs: AccountEnvironmentAttribute) -> Bool { + if lhs.environment != rhs.environment { return false } return true diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountSortOrderAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountSortOrderAttribute.swift index 39ebfb4c92..0f19cf0e01 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountSortOrderAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_AccountSortOrderAttribute.swift @@ -1,26 +1,31 @@ import Foundation import Postbox -public final class AccountSortOrderAttribute: AccountRecordAttribute { +public final class AccountSortOrderAttribute: Codable, Equatable { + enum CodingKeys: String, CodingKey { + case order + } + public let order: Int32 public init(order: Int32) { self.order = order } - public init(decoder: PostboxDecoder) { - self.order = decoder.decodeInt32ForKey("order", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + self.order = (try? container.decode(Int32.self, forKey: .order)) ?? 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.order, forKey: "order") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + + try container.encode(self.order, forKey: .order) } - - public func isEqual(to: AccountRecordAttribute) -> Bool { - guard let to = to as? AccountSortOrderAttribute else { - return false - } - if self.order != to.order { + + public static func ==(lhs: AccountSortOrderAttribute, rhs: AccountSortOrderAttribute) -> Bool { + if lhs.order != rhs.order { return false } return true diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_LoggedOutAccountAttribute.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_LoggedOutAccountAttribute.swift index 5e17ab5c76..7614eb220f 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_LoggedOutAccountAttribute.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_LoggedOutAccountAttribute.swift @@ -1,17 +1,17 @@ import Foundation import Postbox -public final class LoggedOutAccountAttribute: AccountRecordAttribute { +public final class LoggedOutAccountAttribute: Codable, Equatable { public init() { } - public init(decoder: PostboxDecoder) { + public init(from decoder: Decoder) throws { } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { } - - public func isEqual(to: AccountRecordAttribute) -> Bool { - return to is LoggedOutAccountAttribute + + public static func ==(lhs: LoggedOutAccountAttribute, rhs: LoggedOutAccountAttribute) -> Bool { + return true } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_wallapersState.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_wallapersState.swift index b3117097fa..7d7a6af064 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_wallapersState.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_wallapersState.swift @@ -26,7 +26,7 @@ public struct WallpapersState: PreferencesEntry, Equatable { } public extension WallpapersState { - static func update(transaction: AccountManagerModifier, _ f: (WallpapersState) -> WallpapersState) { + static func update(transaction: AccountManagerModifier, _ f: (WallpapersState) -> WallpapersState) { transaction.updateSharedData(SharedDataKeys.wallapersState, { current in let item = (transaction.getSharedData(SharedDataKeys.wallapersState) as? WallpapersState) ?? WallpapersState(wallpapers: []) return f(item) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift index 99dc5a18a4..0f0a569a89 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/AuthTransfer.swift @@ -20,7 +20,7 @@ public enum ExportAuthTransferTokenResult { case passwordRequested(UnauthorizedAccount) } -func _internal_exportAuthTransferToken(accountManager: AccountManager, account: UnauthorizedAccount, otherAccountUserIds: [PeerId.Id], syncContacts: Bool) -> Signal { +func _internal_exportAuthTransferToken(accountManager: AccountManager, account: UnauthorizedAccount, otherAccountUserIds: [PeerId.Id], syncContacts: Bool) -> Signal { return account.network.request(Api.functions.auth.exportLoginToken(apiId: account.networkArguments.apiId, apiHash: account.networkArguments.apiHash, exceptIds: otherAccountUserIds.map({ $0._internalGetInt32Value() }))) |> map(Optional.init) |> `catch` { error -> Signal in diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift index fe4ebd29cb..307023ceaf 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TelegramEngineAuth.swift @@ -11,7 +11,7 @@ public extension TelegramEngineUnauthorized { self.account = account } - public func exportAuthTransferToken(accountManager: AccountManager, otherAccountUserIds: [PeerId.Id], syncContacts: Bool) -> Signal { + public func exportAuthTransferToken(accountManager: AccountManager, otherAccountUserIds: [PeerId.Id], syncContacts: Bool) -> Signal { return _internal_exportAuthTransferToken(accountManager: accountManager, account: self.account, otherAccountUserIds: otherAccountUserIds, syncContacts: syncContacts) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift index 75bb8fa88b..cc11b9ead1 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Countries.swift @@ -101,7 +101,7 @@ public final class CountriesList: PreferencesEntry, Equatable { } -func _internal_getCountriesList(accountManager: AccountManager, network: Network, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { +func _internal_getCountriesList(accountManager: AccountManager, network: Network, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { let fetch: ([Country]?, Int32?) -> Signal<[Country], NoError> = { current, hash in return network.request(Api.functions.help.getCountriesList(langCode: langCode ?? "", hash: hash ?? 0)) |> retryRequest diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift index 606a10cb3a..845530e01d 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift @@ -99,7 +99,7 @@ public enum DownloadAndApplyLocalizationError { case generic } -func _internal_downloadAndApplyLocalization(accountManager: AccountManager, postbox: Postbox, network: Network, languageCode: String) -> Signal { +func _internal_downloadAndApplyLocalization(accountManager: AccountManager, postbox: Postbox, network: Network, languageCode: String) -> Signal { return _internal_requestLocalizationPreview(network: network, identifier: languageCode) |> mapError { _ -> DownloadAndApplyLocalizationError in return .generic diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/TelegramEngineLocalization.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/TelegramEngineLocalization.swift index 21355fc0a5..f07e4a38d2 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/TelegramEngineLocalization.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/TelegramEngineLocalization.swift @@ -9,7 +9,7 @@ public extension TelegramEngine { self.account = account } - public func getCountriesList(accountManager: AccountManager, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { + public func getCountriesList(accountManager: AccountManager, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { return _internal_getCountriesList(accountManager: accountManager, network: self.account.network, langCode: langCode, forceUpdate: forceUpdate) } @@ -29,7 +29,7 @@ public extension TelegramEngine { return _internal_requestLocalizationPreview(network: self.account.network, identifier: identifier) } - public func downloadAndApplyLocalization(accountManager: AccountManager, languageCode: String) -> Signal { + public func downloadAndApplyLocalization(accountManager: AccountManager, languageCode: String) -> Signal { return _internal_downloadAndApplyLocalization(accountManager: accountManager, postbox: self.account.postbox, network: self.account.network, languageCode: languageCode) } } @@ -43,7 +43,7 @@ public extension TelegramEngineUnauthorized { self.account = account } - public func getCountriesList(accountManager: AccountManager, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { + public func getCountriesList(accountManager: AccountManager, langCode: String?, forceUpdate: Bool = false) -> Signal<[Country], NoError> { return _internal_getCountriesList(accountManager: accountManager, network: self.account.network, langCode: langCode, forceUpdate: forceUpdate) } @@ -55,7 +55,7 @@ public extension TelegramEngineUnauthorized { return _internal_currentlySuggestedLocalization(network: self.account.network, extractKeys: extractKeys) } - public func downloadAndApplyLocalization(accountManager: AccountManager, languageCode: String) -> Signal { + public func downloadAndApplyLocalization(accountManager: AccountManager, languageCode: String) -> Signal { return _internal_downloadAndApplyLocalization(accountManager: accountManager, postbox: self.account.postbox, network: self.account.network, languageCode: languageCode) } } diff --git a/submodules/TelegramCore/Sources/Themes.swift b/submodules/TelegramCore/Sources/Themes.swift index 7da9ac24dc..e6250c214e 100644 --- a/submodules/TelegramCore/Sources/Themes.swift +++ b/submodules/TelegramCore/Sources/Themes.swift @@ -12,7 +12,7 @@ let telegramThemeFormat = "ios" let telegramThemeFileExtension = "tgios-theme" #endif -public func telegramThemes(postbox: Postbox, network: Network, accountManager: AccountManager?, forceUpdate: Bool = false) -> Signal<[TelegramTheme], NoError> { +public func telegramThemes(postbox: Postbox, network: Network, accountManager: AccountManager?, forceUpdate: Bool = false) -> Signal<[TelegramTheme], NoError> { let fetch: ([TelegramTheme]?, Int32?) -> Signal<[TelegramTheme], NoError> = { current, hash in network.request(Api.functions.account.getThemes(format: telegramThemeFormat, hash: hash ?? 0)) |> retryRequest @@ -130,7 +130,7 @@ private func checkThemeUpdated(network: Network, theme: TelegramTheme) -> Signal } } -private func saveUnsaveTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme, unsave: Bool) -> Signal { +private func saveUnsaveTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme, unsave: Bool) -> Signal { return account.postbox.transaction { transaction -> Signal in let entries = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudThemes) var items = entries.map { $0.contents as! TelegramTheme } @@ -372,7 +372,7 @@ public func createTheme(account: Account, title: String, resource: MediaResource } } -public func updateTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme, title: String?, slug: String?, resource: MediaResource?, thumbnailData: Data? = nil, settings: TelegramThemeSettings?) -> Signal { +public func updateTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme, title: String?, slug: String?, resource: MediaResource?, thumbnailData: Data? = nil, settings: TelegramThemeSettings?) -> Signal { guard title != nil || slug != nil || resource != nil else { return .complete() } @@ -468,15 +468,15 @@ public func updateTheme(account: Account, accountManager: AccountManager, theme: } } -public func saveThemeInteractively(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { +public func saveThemeInteractively(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { return saveUnsaveTheme(account: account, accountManager: accountManager, theme: theme, unsave: false) } -public func deleteThemeInteractively(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { +public func deleteThemeInteractively(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { return saveUnsaveTheme(account: account, accountManager: accountManager, theme: theme, unsave: true) } -public func applyTheme(accountManager: AccountManager, account: Account, theme: TelegramTheme?, autoNight: Bool = false) -> Signal { +public func applyTheme(accountManager: AccountManager, account: Account, theme: TelegramTheme?, autoNight: Bool = false) -> Signal { return accountManager.transaction { transaction -> Signal in transaction.updateSharedData(SharedDataKeys.themeSettings, { _ in return ThemeSettings(currentTheme: theme) @@ -491,7 +491,7 @@ public func applyTheme(accountManager: AccountManager, account: Account, theme: |> switchToLatest } -func managedThemesUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { +func managedThemesUpdates(accountManager: AccountManager, postbox: Postbox, network: Network) -> Signal { let currentTheme = Atomic(value: nil) return accountManager.sharedData(keys: [SharedDataKeys.themeSettings]) |> map { sharedData -> TelegramTheme? in @@ -559,7 +559,7 @@ private func areThemesEqual(_ lhs: TelegramTheme, _ rhs: TelegramTheme) -> Bool return true } -public func actualizedTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { +public func actualizedTheme(account: Account, accountManager: AccountManager, theme: TelegramTheme) -> Signal { var currentTheme = theme return accountManager.sharedData(keys: [SharedDataKeys.themeSettings]) |> mapToSignal { sharedData -> Signal in diff --git a/submodules/TelegramNotices/BUILD b/submodules/TelegramNotices/BUILD index 351f442adf..5a8b8127a4 100644 --- a/submodules/TelegramNotices/BUILD +++ b/submodules/TelegramNotices/BUILD @@ -11,6 +11,7 @@ swift_library( ], deps = [ "//submodules/Postbox:Postbox", + "//submodules/TelegramCore:TelegramCore", "//submodules/SSignalKit/SwiftSignalKit:SwiftSignalKit", "//submodules/TelegramPermissions:TelegramPermissions", ], diff --git a/submodules/TelegramNotices/Sources/Notices.swift b/submodules/TelegramNotices/Sources/Notices.swift index af36a3f519..f5d7855046 100644 --- a/submodules/TelegramNotices/Sources/Notices.swift +++ b/submodules/TelegramNotices/Sources/Notices.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit import TelegramPermissions @@ -318,7 +319,7 @@ public struct ApplicationSpecificNotice { } } - public static func getBotPaymentLiability(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func getBotPaymentLiability(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.botPaymentLiabilityNotice(peerId: peerId)) as? ApplicationSpecificBoolNotice { return true @@ -328,13 +329,13 @@ public struct ApplicationSpecificNotice { } } - public static func setBotPaymentLiability(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func setBotPaymentLiability(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.botPaymentLiabilityNotice(peerId: peerId), ApplicationSpecificBoolNotice()) } } - public static func getBotGameNotice(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func getBotGameNotice(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.botGameNotice(peerId: peerId)) as? ApplicationSpecificBoolNotice { return true @@ -344,13 +345,13 @@ public struct ApplicationSpecificNotice { } } - public static func setBotGameNotice(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func setBotGameNotice(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.botGameNotice(peerId: peerId), ApplicationSpecificBoolNotice()) } } - public static func getInlineBotLocationRequest(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func getInlineBotLocationRequest(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Int32? in if let notice = transaction.getNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId)) as? ApplicationSpecificTimestampNotice { return notice.value @@ -360,7 +361,7 @@ public struct ApplicationSpecificNotice { } } - public static func inlineBotLocationRequestStatus(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func inlineBotLocationRequestStatus(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.noticeEntry(key: ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId)) |> map { view -> Bool in guard let value = view.value as? ApplicationSpecificTimestampNotice else { @@ -374,7 +375,7 @@ public struct ApplicationSpecificNotice { } } - public static func updateInlineBotLocationRequestState(accountManager: AccountManager, peerId: PeerId, timestamp: Int32) -> Signal { + public static func updateInlineBotLocationRequestState(accountManager: AccountManager, peerId: PeerId, timestamp: Int32) -> Signal { return accountManager.transaction { transaction -> Bool in if let notice = transaction.getNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId)) as? ApplicationSpecificTimestampNotice, (notice.value == 0 || timestamp <= notice.value + 10 * 60) { return false @@ -386,13 +387,13 @@ public struct ApplicationSpecificNotice { } } - public static func setInlineBotLocationRequest(accountManager: AccountManager, peerId: PeerId, value: Int32) -> Signal { + public static func setInlineBotLocationRequest(accountManager: AccountManager, peerId: PeerId, value: Int32) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId), ApplicationSpecificTimestampNotice(value: value)) } } - public static func getSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { + public static func getSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage()) as? ApplicationSpecificBoolNotice { return true @@ -402,17 +403,17 @@ public struct ApplicationSpecificNotice { } } - public static func setSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { + public static func setSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), ApplicationSpecificBoolNotice()) } } - public static func setSecretChatInlineBotUsage(transaction: AccountManagerModifier) { + public static func setSecretChatInlineBotUsage(transaction: AccountManagerModifier) { transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), ApplicationSpecificBoolNotice()) } - public static func getSecretChatLinkPreviews(accountManager: AccountManager) -> Signal { + public static func getSecretChatLinkPreviews(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool? in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews()) as? ApplicationSpecificVariantNotice { return value.value @@ -430,13 +431,13 @@ public struct ApplicationSpecificNotice { } } - public static func setSecretChatLinkPreviews(accountManager: AccountManager, value: Bool) -> Signal { + public static func setSecretChatLinkPreviews(accountManager: AccountManager, value: Bool) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), ApplicationSpecificVariantNotice(value: value)) } } - public static func setSecretChatLinkPreviews(transaction: AccountManagerModifier, value: Bool) { + public static func setSecretChatLinkPreviews(transaction: AccountManagerModifier, value: Bool) { transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), ApplicationSpecificVariantNotice(value: value)) } @@ -444,7 +445,7 @@ public struct ApplicationSpecificNotice { return ApplicationSpecificNoticeKeys.secretChatLinkPreviews() } - public static func getChatMediaMediaRecordingTips(accountManager: AccountManager) -> Signal { + public static func getChatMediaMediaRecordingTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips()) as? ApplicationSpecificCounterNotice { return value.value @@ -454,7 +455,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementChatMediaMediaRecordingTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementChatMediaMediaRecordingTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips()) as? ApplicationSpecificCounterNotice { @@ -466,7 +467,7 @@ public struct ApplicationSpecificNotice { } } - public static func getArchiveChatTips(accountManager: AccountManager) -> Signal { + public static func getArchiveChatTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.archiveChatTips()) as? ApplicationSpecificCounterNotice { return value.value @@ -476,7 +477,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementArchiveChatTips(accountManager: AccountManager, count: Int = 1) -> Signal { + public static func incrementArchiveChatTips(accountManager: AccountManager, count: Int = 1) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.archiveChatTips()) as? ApplicationSpecificCounterNotice { @@ -491,7 +492,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementChatFolderTips(accountManager: AccountManager, count: Int = 1) -> Signal { + public static func incrementChatFolderTips(accountManager: AccountManager, count: Int = 1) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatFolderTips()) as? ApplicationSpecificCounterNotice { @@ -506,7 +507,7 @@ public struct ApplicationSpecificNotice { } } - public static func setArchiveIntroDismissed(transaction: AccountManagerModifier, value: Bool) { + public static func setArchiveIntroDismissed(transaction: AccountManagerModifier, value: Bool) { transaction.setNotice(ApplicationSpecificNoticeKeys.archiveIntroDismissed(), ApplicationSpecificVariantNotice(value: value)) } @@ -514,7 +515,7 @@ public struct ApplicationSpecificNotice { return ApplicationSpecificNoticeKeys.archiveIntroDismissed() } - public static func getProfileCallTips(accountManager: AccountManager) -> Signal { + public static func getProfileCallTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips()) as? ApplicationSpecificCounterNotice { return value.value @@ -524,7 +525,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementProfileCallTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementProfileCallTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips()) as? ApplicationSpecificCounterNotice { @@ -536,7 +537,7 @@ public struct ApplicationSpecificNotice { } } - public static func getSetPublicChannelLink(accountManager: AccountManager) -> Signal { + public static func getSetPublicChannelLink(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips()) as? ApplicationSpecificCounterNotice { return value.value < 1 @@ -546,13 +547,13 @@ public struct ApplicationSpecificNotice { } } - public static func markAsSeenSetPublicChannelLink(accountManager: AccountManager) -> Signal { + public static func markAsSeenSetPublicChannelLink(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.profileCallTips(), ApplicationSpecificCounterNotice(value: 1)) } } - public static func getProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { + public static func getProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment()) as? ApplicationSpecificBoolNotice { return true @@ -562,13 +563,13 @@ public struct ApplicationSpecificNotice { } } - public static func setProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { + public static func setProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment(), ApplicationSpecificBoolNotice()) } } - public static func getPsaAcknowledgment(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func getPsaAcknowledgment(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.psaAdsAcknowledgment(peerId: peerId)) as? ApplicationSpecificBoolNotice { return true @@ -578,13 +579,13 @@ public struct ApplicationSpecificNotice { } } - public static func setPsaAcknowledgment(accountManager: AccountManager, peerId: PeerId) -> Signal { + public static func setPsaAcknowledgment(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.psaAdsAcknowledgment(peerId: peerId), ApplicationSpecificBoolNotice()) } } - public static func getPasscodeLockTips(accountManager: AccountManager) -> Signal { + public static func getPasscodeLockTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.passcodeLockTips()) as? ApplicationSpecificBoolNotice { return true @@ -594,7 +595,7 @@ public struct ApplicationSpecificNotice { } } - public static func setPasscodeLockTips(accountManager: AccountManager) -> Signal { + public static func setPasscodeLockTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.passcodeLockTips(), ApplicationSpecificBoolNotice()) } @@ -604,7 +605,7 @@ public struct ApplicationSpecificNotice { return permission.noticeKey } - public static func setPermissionWarning(accountManager: AccountManager, permission: PermissionKind, value: Int32) { + public static func setPermissionWarning(accountManager: AccountManager, permission: PermissionKind, value: Int32) { guard let noticeKey = permission.noticeKey else { return } @@ -621,7 +622,7 @@ public struct ApplicationSpecificNotice { } } - public static func getVolumeButtonToUnmute(accountManager: AccountManager) -> Signal { + public static func getVolumeButtonToUnmute(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip()) as? ApplicationSpecificBoolNotice { return true @@ -631,13 +632,13 @@ public struct ApplicationSpecificNotice { } } - public static func setVolumeButtonToUnmute(accountManager: AccountManager) { + public static func setVolumeButtonToUnmute(accountManager: AccountManager) { let _ = accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip(), ApplicationSpecificBoolNotice()) }.start() } - public static func getCallsTabTip(accountManager: AccountManager) -> Signal { + public static func getCallsTabTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.callsTabTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -647,7 +648,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementCallsTabTips(accountManager: AccountManager, count: Int = 1) -> Signal { + public static func incrementCallsTabTips(accountManager: AccountManager, count: Int = 1) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.callsTabTip()) as? ApplicationSpecificCounterNotice { @@ -662,14 +663,14 @@ public struct ApplicationSpecificNotice { } } - public static func setCallsTabTip(accountManager: AccountManager) -> Signal { + public static func setCallsTabTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.callsTabTip(), ApplicationSpecificBoolNotice()) } } - public static func getChatMessageSearchResultsTip(accountManager: AccountManager) -> Signal { + public static func getChatMessageSearchResultsTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -679,7 +680,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementChatMessageSearchResultsTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementChatMessageSearchResultsTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip()) as? ApplicationSpecificCounterNotice { @@ -691,7 +692,7 @@ public struct ApplicationSpecificNotice { } } - public static func getChatMessageOptionsTip(accountManager: AccountManager) -> Signal { + public static func getChatMessageOptionsTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -701,7 +702,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementChatMessageOptionsTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementChatMessageOptionsTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { @@ -713,7 +714,7 @@ public struct ApplicationSpecificNotice { } } - public static func getChatTextSelectionTips(accountManager: AccountManager) -> Signal { + public static func getChatTextSelectionTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -723,7 +724,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementChatTextSelectionTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementChatTextSelectionTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip()) as? ApplicationSpecificCounterNotice { @@ -735,7 +736,7 @@ public struct ApplicationSpecificNotice { } } - public static func getThemeChangeTip(accountManager: AccountManager) -> Signal { + public static func getThemeChangeTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.themeChangeTip()) as? ApplicationSpecificBoolNotice { return true @@ -745,13 +746,13 @@ public struct ApplicationSpecificNotice { } } - public static func markThemeChangeTipAsSeen(accountManager: AccountManager) { + public static func markThemeChangeTipAsSeen(accountManager: AccountManager) { let _ = accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.themeChangeTip(), ApplicationSpecificBoolNotice()) }.start() } - public static func getLocationProximityAlertTip(accountManager: AccountManager) -> Signal { + public static func getLocationProximityAlertTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -761,7 +762,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementLocationProximityAlertTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementLocationProximityAlertTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { @@ -773,7 +774,7 @@ public struct ApplicationSpecificNotice { } } - public static func getNextChatSuggestionTip(accountManager: AccountManager) -> Signal { + public static func getNextChatSuggestionTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip()) as? ApplicationSpecificCounterNotice { return value.value @@ -783,7 +784,7 @@ public struct ApplicationSpecificNotice { } } - public static func incrementNextChatSuggestionTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { + public static func incrementNextChatSuggestionTip(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip()) as? ApplicationSpecificCounterNotice { @@ -795,7 +796,7 @@ public struct ApplicationSpecificNotice { } } - public static func dismissedTrendingStickerPacks(accountManager: AccountManager) -> Signal<[Int64]?, NoError> { + public static func dismissedTrendingStickerPacks(accountManager: AccountManager) -> Signal<[Int64]?, NoError> { return accountManager.noticeEntry(key: ApplicationSpecificNoticeKeys.dismissedTrendingStickerPacks()) |> map { view -> [Int64]? in if let value = view.value as? ApplicationSpecificInt64ArrayNotice { @@ -806,13 +807,13 @@ public struct ApplicationSpecificNotice { } } - public static func setDismissedTrendingStickerPacks(accountManager: AccountManager, values: [Int64]) -> Signal { + public static func setDismissedTrendingStickerPacks(accountManager: AccountManager, values: [Int64]) -> Signal { return accountManager.transaction { transaction -> Void in transaction.setNotice(ApplicationSpecificNoticeKeys.dismissedTrendingStickerPacks(), ApplicationSpecificInt64ArrayNotice(values: values)) } } - public static func reset(accountManager: AccountManager) -> Signal { + public static func reset(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in } } diff --git a/submodules/TelegramPresentationData/Sources/PresentationData.swift b/submodules/TelegramPresentationData/Sources/PresentationData.swift index 61181b1072..18a9767964 100644 --- a/submodules/TelegramPresentationData/Sources/PresentationData.swift +++ b/submodules/TelegramPresentationData/Sources/PresentationData.swift @@ -225,7 +225,7 @@ public final class InitialPresentationDataAndSettings { } } -public func currentPresentationDataAndSettings(accountManager: AccountManager, systemUserInterfaceStyle: WindowUserInterfaceStyle) -> Signal { +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 { @@ -561,7 +561,7 @@ public func chatServiceBackgroundColor(wallpaper: TelegramWallpaper, mediaBox: M } } -public func updatedPresentationData(accountManager: AccountManager, applicationInForeground: Signal, systemUserInterfaceStyle: Signal) -> Signal { +public func updatedPresentationData(accountManager: AccountManager, applicationInForeground: Signal, systemUserInterfaceStyle: Signal) -> Signal { return combineLatest(accountManager.sharedData(keys: [SharedDataKeys.localizationSettings, ApplicationSpecificSharedDataKeys.presentationThemeSettings, ApplicationSpecificSharedDataKeys.contactSynchronizationSettings]), systemUserInterfaceStyle) |> mapToSignal { sharedData, systemUserInterfaceStyle -> Signal in let themeSettings: PresentationThemeSettings diff --git a/submodules/TelegramUI/Sources/AppDelegate.swift b/submodules/TelegramUI/Sources/AppDelegate.swift index e2bd3ad585..e8b0702b72 100644 --- a/submodules/TelegramUI/Sources/AppDelegate.swift +++ b/submodules/TelegramUI/Sources/AppDelegate.swift @@ -683,8 +683,8 @@ final class SharedApplicationContext { UINavigationController.attemptRotationToDeviceOrientation() }) - let accountManagerSignal = Signal { subscriber in - let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: false, isReadOnly: false) + let accountManagerSignal = Signal, NoError> { subscriber in + let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: false, isReadOnly: false) return (upgradedAccounts(accountManager: accountManager, rootPath: rootPath, encryptionParameters: encryptionParameters) |> deliverOnMainQueue).start(next: { progress in if self.dataImportSplash == nil { @@ -776,7 +776,7 @@ final class SharedApplicationContext { |> take(1) |> deliverOnMainQueue |> take(1) - |> mapToSignal { accountManager -> Signal<(AccountManager, InitialPresentationDataAndSettings), NoError> in + |> mapToSignal { accountManager -> Signal<(AccountManager, InitialPresentationDataAndSettings), NoError> in var systemUserInterfaceStyle: WindowUserInterfaceStyle = .light if #available(iOS 13.0, *) { if let traitCollection = window.rootViewController?.traitCollection { @@ -1192,7 +1192,7 @@ final class SharedApplicationContext { let logoutDataSignal: Signal<(AccountManager, Set), NoError> = self.sharedContextPromise.get() |> take(1) - |> mapToSignal { sharedContext -> Signal<(AccountManager, Set), NoError> in + |> mapToSignal { sharedContext -> Signal<(AccountManager, Set), NoError> in return sharedContext.sharedContext.activeAccountContexts |> map { _, accounts, _ -> Set in return Set(accounts.map { $0.1.account.peerId }) @@ -1203,7 +1203,7 @@ final class SharedApplicationContext { } return updated } - |> map { loggedOutAccountPeerIds -> (AccountManager, Set) in + |> map { loggedOutAccountPeerIds -> (AccountManager, Set) in return (sharedContext.sharedContext.accountManager, loggedOutAccountPeerIds) } } diff --git a/submodules/TelegramUI/Sources/ApplicationContext.swift b/submodules/TelegramUI/Sources/ApplicationContext.swift index fc98d9967c..8b53fab81c 100644 --- a/submodules/TelegramUI/Sources/ApplicationContext.swift +++ b/submodules/TelegramUI/Sources/ApplicationContext.swift @@ -148,7 +148,7 @@ final class AuthorizedApplicationContext { private var showCallsTabDisposable: Disposable? private var enablePostboxTransactionsDiposable: Disposable? - init(sharedApplicationContext: SharedApplicationContext, mainWindow: Window1, watchManagerArguments: Signal, context: AccountContextImpl, accountManager: AccountManager, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) { + init(sharedApplicationContext: SharedApplicationContext, mainWindow: Window1, watchManagerArguments: Signal, context: AccountContextImpl, accountManager: AccountManager, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) { self.sharedApplicationContext = sharedApplicationContext setupLegacyComponents(context: context) diff --git a/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift b/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift index b0acbe208f..cd59666642 100644 --- a/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift +++ b/submodules/TelegramUI/Sources/AuthorizationSequenceSplashController.swift @@ -15,7 +15,7 @@ final class AuthorizationSequenceSplashController: ViewController { return self.displayNode as! AuthorizationSequenceSplashControllerNode } - private let accountManager: AccountManager + private let accountManager: AccountManager private let account: UnauthorizedAccount private let theme: PresentationTheme @@ -28,7 +28,7 @@ final class AuthorizationSequenceSplashController: ViewController { private let suggestedLocalization = Promise() private let activateLocalizationDisposable = MetaDisposable() - init(accountManager: AccountManager, account: UnauthorizedAccount, theme: PresentationTheme) { + init(accountManager: AccountManager, account: UnauthorizedAccount, theme: PresentationTheme) { self.accountManager = accountManager self.account = account self.theme = theme diff --git a/submodules/TelegramUI/Sources/ChatLinkPreview.swift b/submodules/TelegramUI/Sources/ChatLinkPreview.swift index 45cf4ee76c..30bb9cccff 100644 --- a/submodules/TelegramUI/Sources/ChatLinkPreview.swift +++ b/submodules/TelegramUI/Sources/ChatLinkPreview.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit import TelegramNotices @@ -11,7 +12,7 @@ final class InteractiveChatLinkPreviewsResult { } } -func interactiveChatLinkPreviewsEnabled(accountManager: AccountManager, displayAlert: @escaping (InteractiveChatLinkPreviewsResult) -> Void) -> Signal { +func interactiveChatLinkPreviewsEnabled(accountManager: AccountManager, displayAlert: @escaping (InteractiveChatLinkPreviewsResult) -> Void) -> Signal { return ApplicationSpecificNotice.getSecretChatLinkPreviews(accountManager: accountManager) |> mapToSignal { value -> Signal in if let value = value { diff --git a/submodules/TelegramUI/Sources/FetchCachedRepresentations.swift b/submodules/TelegramUI/Sources/FetchCachedRepresentations.swift index e5945e9be1..111afb89c4 100644 --- a/submodules/TelegramUI/Sources/FetchCachedRepresentations.swift +++ b/submodules/TelegramUI/Sources/FetchCachedRepresentations.swift @@ -399,7 +399,7 @@ private func fetchCachedBlurredWallpaperRepresentation(resource: MediaResource, }) |> runOn(Queue.concurrentDefaultQueue()) } -public func fetchCachedSharedResourceRepresentation(accountManager: AccountManager, resource: MediaResource, representation: CachedMediaResourceRepresentation) -> Signal { +public func fetchCachedSharedResourceRepresentation(accountManager: AccountManager, resource: MediaResource, representation: CachedMediaResourceRepresentation) -> Signal { if let representation = representation as? CachedScaledImageRepresentation { return accountManager.mediaBox.resourceData(resource, option: .complete(waitUntilFetchStatus: false)) |> mapToSignal { data -> Signal in diff --git a/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift b/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift index dcf97d441c..b6863bb552 100644 --- a/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift +++ b/submodules/TelegramUI/Sources/ManageSharedAccountInfo.swift @@ -64,7 +64,7 @@ private func accountInfo(account: Account) -> Signal } } -func sharedAccountInfos(accountManager: AccountManager, accounts: Signal<[Account], NoError>) -> Signal { +func sharedAccountInfos(accountManager: AccountManager, accounts: Signal<[Account], NoError>) -> Signal { return combineLatest(accountManager.sharedData(keys: [SharedDataKeys.proxySettings]), accounts) |> take(1) |> mapToSignal { sharedData, accounts -> Signal in diff --git a/submodules/TelegramUI/Sources/MediaManager.swift b/submodules/TelegramUI/Sources/MediaManager.swift index 3f1d6a3a3b..0b94cf60fd 100644 --- a/submodules/TelegramUI/Sources/MediaManager.swift +++ b/submodules/TelegramUI/Sources/MediaManager.swift @@ -60,7 +60,7 @@ public final class MediaManagerImpl: NSObject, MediaManager { private let queue = Queue.mainQueue() - private let accountManager: AccountManager + private let accountManager: AccountManager private let inForeground: Signal private let presentationData: Signal @@ -188,7 +188,7 @@ public final class MediaManagerImpl: NSObject, MediaManager { public let galleryHiddenMediaManager: GalleryHiddenMediaManager = GalleryHiddenMediaManagerImpl() - init(accountManager: AccountManager, inForeground: Signal, presentationData: Signal) { + init(accountManager: AccountManager, inForeground: Signal, presentationData: Signal) { self.accountManager = accountManager self.inForeground = inForeground self.presentationData = presentationData diff --git a/submodules/TelegramUI/Sources/NotificationContentContext.swift b/submodules/TelegramUI/Sources/NotificationContentContext.swift index fa663977fc..7389aea8f2 100644 --- a/submodules/TelegramUI/Sources/NotificationContentContext.swift +++ b/submodules/TelegramUI/Sources/NotificationContentContext.swift @@ -94,7 +94,7 @@ public final class NotificationViewControllerImpl { if sharedAccountContext == nil { initializeAccountManagement() - let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) + let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) var initialPresentationDataAndSettings: InitialPresentationDataAndSettings? let semaphore = DispatchSemaphore(value: 0) diff --git a/submodules/TelegramUI/Sources/OverlayPlayerControlsNode.swift b/submodules/TelegramUI/Sources/OverlayPlayerControlsNode.swift index 2f648a2f48..e17807d601 100644 --- a/submodules/TelegramUI/Sources/OverlayPlayerControlsNode.swift +++ b/submodules/TelegramUI/Sources/OverlayPlayerControlsNode.swift @@ -86,7 +86,7 @@ private func stringsForDisplayData(_ data: SharedMediaPlaybackDisplayData?, pres } final class OverlayPlayerControlsNode: ASDisplayNode { - private let accountManager: AccountManager + private let accountManager: AccountManager private let postbox: Postbox private var presentationData: PresentationData @@ -153,7 +153,7 @@ final class OverlayPlayerControlsNode: ASDisplayNode { private var validLayout: (width: CGFloat, leftInset: CGFloat, rightInset: CGFloat, maxHeight: CGFloat)? - init(account: Account, accountManager: AccountManager, presentationData: PresentationData, status: Signal<(Account, SharedMediaPlayerItemPlaybackStateOrLoading, MediaManagerPlayerType)?, NoError>) { + init(account: Account, accountManager: AccountManager, presentationData: PresentationData, status: Signal<(Account, SharedMediaPlayerItemPlaybackStateOrLoading, MediaManagerPlayerType)?, NoError>) { self.accountManager = accountManager self.postbox = account.postbox self.presentationData = presentationData diff --git a/submodules/TelegramUI/Sources/ShareExtensionContext.swift b/submodules/TelegramUI/Sources/ShareExtensionContext.swift index 7db09e7585..559013266f 100644 --- a/submodules/TelegramUI/Sources/ShareExtensionContext.swift +++ b/submodules/TelegramUI/Sources/ShareExtensionContext.swift @@ -205,7 +205,7 @@ public class ShareRootControllerImpl { let internalContext: InternalContext - let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) + let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata", isTemporary: true, isReadOnly: false) if let globalInternalContext = globalInternalContext { internalContext = globalInternalContext diff --git a/submodules/TelegramUI/Sources/SharedAccountContext.swift b/submodules/TelegramUI/Sources/SharedAccountContext.swift index b6fd0e5700..d88a1b68dc 100644 --- a/submodules/TelegramUI/Sources/SharedAccountContext.swift +++ b/submodules/TelegramUI/Sources/SharedAccountContext.swift @@ -57,7 +57,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { public let applicationBindings: TelegramApplicationBindings public let sharedContainerPath: String public let basePath: String - public let accountManager: AccountManager + public let accountManager: AccountManager public let appLockContext: AppLockContext private let navigateToChatImpl: (AccountRecordId, PeerId, MessageId?) -> Void @@ -161,7 +161,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { private var spotlightDataContext: SpotlightDataContext? private var widgetDataContext: WidgetDataContext? - public init(mainWindow: Window1?, sharedContainerPath: String, basePath: String, encryptionParameters: ValueBoxEncryptionParameters, accountManager: AccountManager, appLockContext: AppLockContext, applicationBindings: TelegramApplicationBindings, initialPresentationDataAndSettings: InitialPresentationDataAndSettings, networkArguments: NetworkInitializationArguments, rootPath: String, legacyBasePath: String?, apsNotificationToken: Signal, voipNotificationToken: Signal, setNotificationCall: @escaping (PresentationCall?) -> Void, navigateToChat: @escaping (AccountRecordId, PeerId, MessageId?) -> Void, displayUpgradeProgress: @escaping (Float?) -> Void = { _ in }) { + public init(mainWindow: Window1?, sharedContainerPath: String, basePath: String, encryptionParameters: ValueBoxEncryptionParameters, accountManager: AccountManager, appLockContext: AppLockContext, applicationBindings: TelegramApplicationBindings, initialPresentationDataAndSettings: InitialPresentationDataAndSettings, networkArguments: NetworkInitializationArguments, rootPath: String, legacyBasePath: String?, apsNotificationToken: Signal, voipNotificationToken: Signal, setNotificationCall: @escaping (PresentationCall?) -> Void, navigateToChat: @escaping (AccountRecordId, PeerId, MessageId?) -> Void, displayUpgradeProgress: @escaping (Float?) -> Void = { _ in }) { assert(Queue.mainQueue().isCurrent()) precondition(!testHasInstance) @@ -345,13 +345,17 @@ public final class SharedAccountContextImpl: SharedAccountContext { var result: [AccountRecordId: AccountAttributes] = [:] for record in view.records { let isLoggedOut = record.attributes.contains(where: { attribute in - return attribute is LoggedOutAccountAttribute + if case .loggedOut = attribute { + return true + } else { + return false + } }) if isLoggedOut { continue } let isTestingEnvironment = record.attributes.contains(where: { attribute in - if let attribute = attribute as? AccountEnvironmentAttribute, case .test = attribute.environment { + if case let .environment(environment) = attribute, case .test = environment.environment { return true } else { return false @@ -360,17 +364,17 @@ public final class SharedAccountContextImpl: SharedAccountContext { var backupData: AccountBackupData? var sortIndex: Int32 = 0 for attribute in record.attributes { - if let attribute = attribute as? AccountSortOrderAttribute { - sortIndex = attribute.order - } else if let attribute = attribute as? AccountBackupDataAttribute { - backupData = attribute.data + if case let .sortOrder(sortOrder) = attribute { + sortIndex = sortOrder.order + } else if case let .backupData(backupDataValue) = attribute { + backupData = backupDataValue.data } } result[record.id] = AccountAttributes(sortIndex: sortIndex, isTestingEnvironment: isTestingEnvironment, backupData: backupData) } let authRecord: (AccountRecordId, Bool)? = view.currentAuthAccount.flatMap({ authAccount in let isTestingEnvironment = authAccount.attributes.contains(where: { attribute in - if let attribute = attribute as? AccountEnvironmentAttribute, case .test = attribute.environment { + if case let .environment(environment) = attribute, case .test = environment.environment { return true } else { return false @@ -807,8 +811,14 @@ public final class SharedAccountContextImpl: SharedAccountContext { guard let record = record else { return nil } - var attributes = record.attributes.filter({ !($0 is AccountBackupDataAttribute) }) - attributes.append(AccountBackupDataAttribute(data: backupData)) + var attributes: [TelegramAccountManagerTypes.Attribute] = record.attributes.filter { attribute in + if case .backupData = attribute { + return false + } else { + return true + } + } + attributes.append(.backupData(AccountBackupDataAttribute(data: backupData))) return AccountRecord(id: record.id, attributes: attributes, temporarySessionId: record.temporarySessionId) }) } @@ -920,7 +930,7 @@ public final class SharedAccountContextImpl: SharedAccountContext { public func beginNewAuth(testingEnvironment: Bool) { let _ = self.accountManager.transaction({ transaction -> Void in - let _ = transaction.createAuth([AccountEnvironmentAttribute(environment: testingEnvironment ? .test : .production)]) + let _ = transaction.createAuth([.environment(AccountEnvironmentAttribute(environment: testingEnvironment ? .test : .production))]) }).start() } diff --git a/submodules/TelegramUI/Sources/SharedNotificationManager.swift b/submodules/TelegramUI/Sources/SharedNotificationManager.swift index e44b071d69..a6c89c34d7 100644 --- a/submodules/TelegramUI/Sources/SharedNotificationManager.swift +++ b/submodules/TelegramUI/Sources/SharedNotificationManager.swift @@ -40,7 +40,7 @@ public final class SharedNotificationManager { private var inForeground: Bool = false private var inForegroundDisposable: Disposable? - private var accountManager: AccountManager? + private var accountManager: AccountManager? private var accountsAndKeys: [(Account, Bool, MasterNotificationKey)]? private var accountsAndKeysDisposable: Disposable? diff --git a/submodules/TelegramUI/Sources/SpotlightContacts.swift b/submodules/TelegramUI/Sources/SpotlightContacts.swift index d1e97aeb19..1ad6e86fbc 100644 --- a/submodules/TelegramUI/Sources/SpotlightContacts.swift +++ b/submodules/TelegramUI/Sources/SpotlightContacts.swift @@ -224,12 +224,12 @@ private func manageableSpotlightContacts(appBasePath: String, accounts: Signal<[ private final class SpotlightDataContextImpl { private let queue: Queue private let appBasePath: String - private let accountManager: AccountManager + private let accountManager: AccountManager private let indexStorage: SpotlightIndexStorage private var listDisposable: Disposable? - init(queue: Queue, appBasePath: String, accountManager: AccountManager, accounts: Signal<[Account], NoError>) { + init(queue: Queue, appBasePath: String, accountManager: AccountManager, accounts: Signal<[Account], NoError>) { self.queue = queue self.appBasePath = appBasePath self.accountManager = accountManager @@ -266,7 +266,7 @@ private final class SpotlightDataContextImpl { public final class SpotlightDataContext { private let impl: QueueLocalObject - public init(appBasePath: String, accountManager: AccountManager, accounts: Signal<[Account], NoError>) { + public init(appBasePath: String, accountManager: AccountManager, accounts: Signal<[Account], NoError>) { let queue = Queue() self.impl = QueueLocalObject(queue: queue, generate: { return SpotlightDataContextImpl(queue: queue, appBasePath: appBasePath, accountManager: accountManager, accounts: accounts) diff --git a/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift b/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift index cde6ba0158..0023d3a103 100644 --- a/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift +++ b/submodules/TelegramUI/Sources/StoreDownloadedMedia.swift @@ -149,7 +149,7 @@ private final class DownloadedMediaStoreManagerPrivateImpl { private let appSpecificAssetCollectionValue: Promise private let storeSettings = Promise() - init(queue: Queue, postbox: Postbox, accountManager: AccountManager) { + init(queue: Queue, postbox: Postbox, accountManager: AccountManager) { self.queue = queue self.postbox = postbox @@ -199,7 +199,7 @@ final class DownloadedMediaStoreManagerImpl: DownloadedMediaStoreManager { private let queue = Queue() private let impl: QueueLocalObject - init(postbox: Postbox, accountManager: AccountManager) { + init(postbox: Postbox, accountManager: AccountManager) { let queue = self.queue self.impl = QueueLocalObject(queue: queue, generate: { return DownloadedMediaStoreManagerPrivateImpl(queue: queue, postbox: postbox, accountManager: accountManager) diff --git a/submodules/TelegramUI/Sources/UpgradedAccounts.swift b/submodules/TelegramUI/Sources/UpgradedAccounts.swift index fc08028067..a02625e868 100644 --- a/submodules/TelegramUI/Sources/UpgradedAccounts.swift +++ b/submodules/TelegramUI/Sources/UpgradedAccounts.swift @@ -110,7 +110,7 @@ private func upgradedSharedDataValue(_ value: PreferencesEntry?) -> PreferencesE } } -public func upgradedAccounts(accountManager: AccountManager, rootPath: String, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { +public func upgradedAccounts(accountManager: AccountManager, rootPath: String, encryptionParameters: ValueBoxEncryptionParameters) -> Signal { return accountManager.transaction { transaction -> (Int32?, AccountRecordId?) in return (transaction.getVersion(), transaction.getCurrent()?.0) } @@ -237,7 +237,7 @@ public func upgradedAccounts(accountManager: AccountManager, rootPath: String, e var index: Int32 = 0 for record in transaction.getRecords() { transaction.updateRecord(record.id, { _ in - return AccountRecord(id: record.id, attributes: record.attributes + [AccountSortOrderAttribute(order: index)], temporarySessionId: record.temporarySessionId) + return AccountRecord(id: record.id, attributes: record.attributes + [.sortOrder(AccountSortOrderAttribute(order: index))], temporarySessionId: record.temporarySessionId) }) index += 1 } diff --git a/submodules/TelegramUIPreferences/Sources/CallListSettings.swift b/submodules/TelegramUIPreferences/Sources/CallListSettings.swift index e40d334a9b..55383bcdbc 100644 --- a/submodules/TelegramUIPreferences/Sources/CallListSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/CallListSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct CallListSettings: PreferencesEntry, Equatable { @@ -72,7 +73,7 @@ public struct CallListSettings: PreferencesEntry, Equatable { } } -public func updateCallListSettingsInteractively(accountManager: AccountManager, _ f: @escaping (CallListSettings) -> CallListSettings) -> Signal { +public func updateCallListSettingsInteractively(accountManager: AccountManager, _ f: @escaping (CallListSettings) -> CallListSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.callListSettings, { entry in let currentSettings: CallListSettings diff --git a/submodules/TelegramUIPreferences/Sources/ContactSynchronizationSettings.swift b/submodules/TelegramUIPreferences/Sources/ContactSynchronizationSettings.swift index 98ae147d31..f80a3851a4 100644 --- a/submodules/TelegramUIPreferences/Sources/ContactSynchronizationSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/ContactSynchronizationSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum ContactsSortOrder: Int32 { @@ -48,7 +49,7 @@ public struct ContactSynchronizationSettings: Equatable, PreferencesEntry { } } -public func updateContactSettingsInteractively(accountManager: AccountManager, _ f: @escaping (ContactSynchronizationSettings) -> ContactSynchronizationSettings) -> Signal { +public func updateContactSettingsInteractively(accountManager: AccountManager, _ f: @escaping (ContactSynchronizationSettings) -> ContactSynchronizationSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.contactSynchronizationSettings, { entry in let currentSettings: ContactSynchronizationSettings diff --git a/submodules/TelegramUIPreferences/Sources/ExperimentalSettings.swift b/submodules/TelegramUIPreferences/Sources/ExperimentalSettings.swift index 53c722b3f2..ace0e5f197 100644 --- a/submodules/TelegramUIPreferences/Sources/ExperimentalSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/ExperimentalSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct ExperimentalSettings: PreferencesEntry, Equatable { @@ -34,7 +35,7 @@ public struct ExperimentalSettings: PreferencesEntry, Equatable { } } -public func updateExperimentalSettingsInteractively(accountManager: AccountManager, _ f: @escaping (ExperimentalSettings) -> ExperimentalSettings) -> Signal { +public func updateExperimentalSettingsInteractively(accountManager: AccountManager, _ f: @escaping (ExperimentalSettings) -> ExperimentalSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalSettings, { entry in let currentSettings: ExperimentalSettings diff --git a/submodules/TelegramUIPreferences/Sources/ExperimentalUISettings.swift b/submodules/TelegramUIPreferences/Sources/ExperimentalUISettings.swift index d08fd83283..bece6cae74 100644 --- a/submodules/TelegramUIPreferences/Sources/ExperimentalUISettings.swift +++ b/submodules/TelegramUIPreferences/Sources/ExperimentalUISettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct ExperimentalUISettings: Equatable, PreferencesEntry { @@ -114,7 +115,7 @@ public struct ExperimentalUISettings: Equatable, PreferencesEntry { } } -public func updateExperimentalUISettingsInteractively(accountManager: AccountManager, _ f: @escaping (ExperimentalUISettings) -> ExperimentalUISettings) -> Signal { +public func updateExperimentalUISettingsInteractively(accountManager: AccountManager, _ f: @escaping (ExperimentalUISettings) -> ExperimentalUISettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.experimentalUISettings, { entry in let currentSettings: ExperimentalUISettings diff --git a/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift b/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift index 3b711ef296..c8473ee338 100644 --- a/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/GeneratedMediaStoreSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct GeneratedMediaStoreSettings: PreferencesEntry, Equatable { @@ -42,7 +43,7 @@ public struct GeneratedMediaStoreSettings: PreferencesEntry, Equatable { } } -public func updateGeneratedMediaStoreSettingsInteractively(accountManager: AccountManager, _ f: @escaping (GeneratedMediaStoreSettings) -> GeneratedMediaStoreSettings) -> Signal { +public func updateGeneratedMediaStoreSettingsInteractively(accountManager: AccountManager, _ f: @escaping (GeneratedMediaStoreSettings) -> GeneratedMediaStoreSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.generatedMediaStoreSettings, { entry in let currentSettings: GeneratedMediaStoreSettings diff --git a/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift b/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift index 6cb40aac97..458f92472e 100644 --- a/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/InAppNotificationSettings.swift @@ -103,7 +103,7 @@ public struct InAppNotificationSettings: PreferencesEntry, Equatable { } } -public func updateInAppNotificationSettingsInteractively(accountManager: AccountManager, _ f: @escaping (InAppNotificationSettings) -> InAppNotificationSettings) -> Signal { +public func updateInAppNotificationSettingsInteractively(accountManager: AccountManager, _ f: @escaping (InAppNotificationSettings) -> InAppNotificationSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.inAppNotificationSettings, { entry in let currentSettings: InAppNotificationSettings diff --git a/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift b/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift index b2b696215a..24196f6a02 100644 --- a/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/InstantPagePresentationSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum InstantPageThemeType: Int32 { @@ -98,7 +99,7 @@ public final class InstantPagePresentationSettings: PreferencesEntry, Equatable } } -public func updateInstantPagePresentationSettingsInteractively(accountManager: AccountManager, _ f: @escaping (InstantPagePresentationSettings) -> InstantPagePresentationSettings) -> Signal { +public func updateInstantPagePresentationSettingsInteractively(accountManager: AccountManager, _ f: @escaping (InstantPagePresentationSettings) -> InstantPagePresentationSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.instantPagePresentationSettings, { entry in let currentSettings: InstantPagePresentationSettings diff --git a/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift b/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift index 77ba26eea7..221f946fe0 100644 --- a/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/IntentsSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct IntentsSettings: PreferencesEntry, Equatable { @@ -88,7 +89,7 @@ public struct IntentsSettings: PreferencesEntry, Equatable { } -public func updateIntentsSettingsInteractively(accountManager: AccountManager, _ f: @escaping (IntentsSettings) -> IntentsSettings) -> Signal<(IntentsSettings?, IntentsSettings?), NoError> { +public func updateIntentsSettingsInteractively(accountManager: AccountManager, _ f: @escaping (IntentsSettings) -> IntentsSettings) -> Signal<(IntentsSettings?, IntentsSettings?), NoError> { return accountManager.transaction { transaction -> (IntentsSettings?, IntentsSettings?) in var previousSettings: IntentsSettings? = nil var updatedSettings: IntentsSettings? = nil diff --git a/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift b/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift index 2e5d132c07..c6a262d0a7 100644 --- a/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MediaAutoDownloadSettings.swift @@ -257,7 +257,7 @@ private func presetsWithAutodownloadSettings(_ autodownloadSettings: Autodownloa return MediaAutoDownloadPresets(low: categoriesWithAutodownloadPreset(autodownloadSettings.lowPreset, preset: .low), medium: categoriesWithAutodownloadPreset(autodownloadSettings.mediumPreset, preset: .medium), high: categoriesWithAutodownloadPreset(autodownloadSettings.highPreset, preset: .high)) } -public func updateMediaDownloadSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MediaAutoDownloadSettings) -> MediaAutoDownloadSettings) -> Signal { +public func updateMediaDownloadSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MediaAutoDownloadSettings) -> MediaAutoDownloadSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings, { entry in let currentSettings: MediaAutoDownloadSettings diff --git a/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift b/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift index db6fba2ae2..e1c5f49d42 100644 --- a/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MediaInputSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct MediaInputSettings: PreferencesEntry, Equatable { @@ -38,7 +39,7 @@ public struct MediaInputSettings: PreferencesEntry, Equatable { } } -public func updateMediaInputSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MediaInputSettings) -> MediaInputSettings) -> Signal { +public func updateMediaInputSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MediaInputSettings) -> MediaInputSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.mediaInputSettings, { entry in let currentSettings: MediaInputSettings diff --git a/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift b/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift index d2707fa138..37d28f873f 100644 --- a/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/MusicPlaybackSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum MusicPlaybackSettingsOrder: Int32 { @@ -88,7 +89,7 @@ public struct MusicPlaybackSettings: PreferencesEntry, Equatable { } } -public func updateMusicPlaybackSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MusicPlaybackSettings) -> MusicPlaybackSettings) -> Signal { +public func updateMusicPlaybackSettingsInteractively(accountManager: AccountManager, _ f: @escaping (MusicPlaybackSettings) -> MusicPlaybackSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.musicPlaybackSettings, { entry in let currentSettings: MusicPlaybackSettings diff --git a/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift b/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift index 6d212f46a2..45c1b0dcec 100644 --- a/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/PresentationPasscodeSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct PresentationPasscodeSettings: PreferencesEntry, Equatable { @@ -74,13 +75,13 @@ public struct PresentationPasscodeSettings: PreferencesEntry, Equatable { } } -public func updatePresentationPasscodeSettingsInteractively(accountManager: AccountManager, _ f: @escaping (PresentationPasscodeSettings) -> PresentationPasscodeSettings) -> Signal { +public func updatePresentationPasscodeSettingsInteractively(accountManager: AccountManager, _ f: @escaping (PresentationPasscodeSettings) -> PresentationPasscodeSettings) -> Signal { return accountManager.transaction { transaction -> Void in updatePresentationPasscodeSettingsInternal(transaction: transaction, f) } } -public func updatePresentationPasscodeSettingsInternal(transaction: AccountManagerModifier, _ f: @escaping (PresentationPasscodeSettings) -> PresentationPasscodeSettings) { +public func updatePresentationPasscodeSettingsInternal(transaction: AccountManagerModifier, _ f: @escaping (PresentationPasscodeSettings) -> PresentationPasscodeSettings) { transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationPasscodeSettings, { entry in let currentSettings: PresentationPasscodeSettings if let entry = entry as? PresentationPasscodeSettings { diff --git a/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift b/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift index a61efc7de9..6c36304629 100644 --- a/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/PresentationThemeSettings.swift @@ -693,7 +693,7 @@ public struct PresentationThemeSettings: PreferencesEntry { } } -public func updatePresentationThemeSettingsInteractively(accountManager: AccountManager, _ f: @escaping (PresentationThemeSettings) -> PresentationThemeSettings) -> Signal { +public func updatePresentationThemeSettingsInteractively(accountManager: AccountManager, _ f: @escaping (PresentationThemeSettings) -> PresentationThemeSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.presentationThemeSettings, { entry in let currentSettings: PresentationThemeSettings diff --git a/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift b/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift index 2e2fab0bd1..dff99b50bf 100644 --- a/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift +++ b/submodules/TelegramUIPreferences/Sources/RenderedTotalUnreadCount.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum RenderedTotalUnreadCountType { @@ -21,7 +22,7 @@ public func renderedTotalUnreadCount(inAppSettings: InAppNotificationSettings, t return (totalUnreadState.count(for: inAppSettings.totalUnreadCountDisplayStyle.category, in: inAppSettings.totalUnreadCountDisplayCategory.statsType, with: inAppSettings.totalUnreadCountIncludeTags), type) } -public func renderedTotalUnreadCount(accountManager: AccountManager, postbox: Postbox) -> Signal<(Int32, RenderedTotalUnreadCountType), NoError> { +public func renderedTotalUnreadCount(accountManager: AccountManager, postbox: Postbox) -> Signal<(Int32, RenderedTotalUnreadCountType), NoError> { let unreadCountsKey = PostboxViewKey.unreadCounts(items: [.total(nil)]) return combineLatest(accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.inAppNotificationSettings]), postbox.combinedView(keys: [unreadCountsKey])) |> map { sharedData, view -> (Int32, RenderedTotalUnreadCountType) in diff --git a/submodules/TelegramUIPreferences/Sources/StickerSettings.swift b/submodules/TelegramUIPreferences/Sources/StickerSettings.swift index 4eea5be1da..1f0adf1b4c 100644 --- a/submodules/TelegramUIPreferences/Sources/StickerSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/StickerSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum EmojiStickerSuggestionMode: Int32 { @@ -52,7 +53,7 @@ public struct StickerSettings: PreferencesEntry, Equatable { } } -public func updateStickerSettingsInteractively(accountManager: AccountManager, _ f: @escaping (StickerSettings) -> StickerSettings) -> Signal { +public func updateStickerSettingsInteractively(accountManager: AccountManager, _ f: @escaping (StickerSettings) -> StickerSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.stickerSettings, { entry in let currentSettings: StickerSettings diff --git a/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift b/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift index 91f87db642..3dc6a49852 100644 --- a/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/VoiceCallSettings.swift @@ -71,7 +71,7 @@ public struct VoiceCallSettings: PreferencesEntry, Equatable { } } -public func updateVoiceCallSettingsSettingsInteractively(accountManager: AccountManager, _ f: @escaping (VoiceCallSettings) -> VoiceCallSettings) -> Signal { +public func updateVoiceCallSettingsSettingsInteractively(accountManager: AccountManager, _ f: @escaping (VoiceCallSettings) -> VoiceCallSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.voiceCallSettings, { entry in let currentSettings: VoiceCallSettings diff --git a/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift b/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift index a6d09d5bca..c73fa77c0e 100644 --- a/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WatchPresetSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct WatchPresetSettings: PreferencesEntry, Equatable { @@ -53,7 +54,7 @@ public struct WatchPresetSettings: PreferencesEntry, Equatable { } } -public func updateWatchPresetSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WatchPresetSettings) -> WatchPresetSettings) -> Signal { +public func updateWatchPresetSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WatchPresetSettings) -> WatchPresetSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.watchPresetSettings, { entry in let currentSettings: WatchPresetSettings diff --git a/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift b/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift index 09be868a4c..d2b0082fef 100644 --- a/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WebBrowserSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public struct WebBrowserSettings: PreferencesEntry, Equatable { @@ -42,7 +43,7 @@ public struct WebBrowserSettings: PreferencesEntry, Equatable { } } -public func updateWebBrowserSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WebBrowserSettings) -> WebBrowserSettings) -> Signal { +public func updateWebBrowserSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WebBrowserSettings) -> WebBrowserSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.webBrowserSettings, { entry in let currentSettings: WebBrowserSettings diff --git a/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift b/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift index a21413a4d4..99c3c2b35e 100644 --- a/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift +++ b/submodules/TelegramUIPreferences/Sources/WebSearchSettings.swift @@ -1,5 +1,6 @@ import Foundation import Postbox +import TelegramCore import SwiftSignalKit public enum WebSearchScope: Int32 { @@ -35,7 +36,7 @@ public struct WebSearchSettings: Equatable, PreferencesEntry { } } -public func updateWebSearchSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WebSearchSettings) -> WebSearchSettings) -> Signal { +public func updateWebSearchSettingsInteractively(accountManager: AccountManager, _ f: @escaping (WebSearchSettings) -> WebSearchSettings) -> Signal { return accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSpecificSharedDataKeys.webSearchSettings, { entry in let currentSettings: WebSearchSettings diff --git a/submodules/WallpaperResources/Sources/WallpaperResources.swift b/submodules/WallpaperResources/Sources/WallpaperResources.swift index c7404cd746..97a85afecd 100644 --- a/submodules/WallpaperResources/Sources/WallpaperResources.swift +++ b/submodules/WallpaperResources/Sources/WallpaperResources.swift @@ -17,7 +17,7 @@ import Svg import GradientBackground import GZip -public func wallpaperDatas(account: Account, accountManager: AccountManager, fileReference: FileMediaReference? = nil, representations: [ImageRepresentationWithReference], alwaysShowThumbnailFirst: Bool = false, thumbnail: Bool = false, onlyFullSize: Bool = false, autoFetchFullSize: Bool = false, synchronousLoad: Bool = false) -> Signal<(Data?, Data?, Bool), NoError> { +public func wallpaperDatas(account: Account, accountManager: AccountManager, fileReference: FileMediaReference? = nil, representations: [ImageRepresentationWithReference], alwaysShowThumbnailFirst: Bool = false, thumbnail: Bool = false, onlyFullSize: Bool = false, autoFetchFullSize: Bool = false, synchronousLoad: Bool = false) -> Signal<(Data?, Data?, Bool), NoError> { if let smallestRepresentation = smallestImageRepresentation(representations.map({ $0.representation })), let largestRepresentation = largestImageRepresentation(representations.map({ $0.representation })), let smallestIndex = representations.firstIndex(where: { $0.representation == smallestRepresentation }), let largestIndex = representations.firstIndex(where: { $0.representation == largestRepresentation }) { let maybeFullSize: Signal @@ -168,7 +168,7 @@ public func wallpaperDatas(account: Account, accountManager: AccountManager, fil } } -public func wallpaperImage(account: Account, accountManager: AccountManager, fileReference: FileMediaReference? = nil, representations: [ImageRepresentationWithReference], alwaysShowThumbnailFirst: Bool = false, thumbnail: Bool = false, onlyFullSize: Bool = false, autoFetchFullSize: Bool = false, blurred: Bool = false, synchronousLoad: Bool = false) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { +public func wallpaperImage(account: Account, accountManager: AccountManager, fileReference: FileMediaReference? = nil, representations: [ImageRepresentationWithReference], alwaysShowThumbnailFirst: Bool = false, thumbnail: Bool = false, onlyFullSize: Bool = false, autoFetchFullSize: Bool = false, blurred: Bool = false, synchronousLoad: Bool = false) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { let signal = wallpaperDatas(account: account, accountManager: accountManager, fileReference: fileReference, representations: representations, alwaysShowThumbnailFirst: alwaysShowThumbnailFirst, thumbnail: thumbnail, onlyFullSize: onlyFullSize, autoFetchFullSize: autoFetchFullSize, synchronousLoad: synchronousLoad) return signal @@ -351,7 +351,7 @@ public struct PatternWallpaperArguments: TransformImageCustomArguments { } } -private func patternWallpaperDatas(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<(Data?, Bool), NoError> { +private func patternWallpaperDatas(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<(Data?, Bool), NoError> { var targetRepresentation: ImageRepresentationWithReference? switch mode { case .thumbnail: @@ -444,7 +444,7 @@ private func patternWallpaperDatas(account: Account, accountManager: AccountMana } } -public func patternWallpaperImage(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<((TransformImageArguments) -> DrawingContext?)?, NoError> { +public func patternWallpaperImage(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<((TransformImageArguments) -> DrawingContext?)?, NoError> { return patternWallpaperDatas(account: account, accountManager: accountManager, representations: representations, mode: mode, autoFetchFullSize: autoFetchFullSize) |> mapToSignal { fullSizeData, fullSizeComplete in return patternWallpaperImageInternal(fullSizeData: fullSizeData, fullSizeComplete: fullSizeComplete, mode: mode) @@ -862,7 +862,7 @@ public func photoWallpaper(postbox: Postbox, photoLibraryResource: PhotoLibraryM } } -public func telegramThemeData(account: Account, accountManager: AccountManager, reference: MediaResourceReference, synchronousLoad: Bool = false) -> Signal { +public func telegramThemeData(account: Account, accountManager: AccountManager, reference: MediaResourceReference, synchronousLoad: Bool = false) -> Signal { let maybeFetched = accountManager.mediaBox.resourceData(reference.resource, option: .complete(waitUntilFetchStatus: false), attemptSynchronously: synchronousLoad) return maybeFetched |> take(1) @@ -1064,7 +1064,7 @@ public enum ThemeImageSource { case settings(TelegramThemeSettings) } -public func themeImage(account: Account, accountManager: AccountManager, source: ThemeImageSource, synchronousLoad: Bool = false) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { +public func themeImage(account: Account, accountManager: AccountManager, source: ThemeImageSource, synchronousLoad: Bool = false) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { let theme: Signal<(PresentationTheme?, Data?), NoError> switch source { @@ -1291,7 +1291,7 @@ public func themeImage(account: Account, accountManager: AccountManager, source: } } -public func themeIconImage(account: Account, accountManager: AccountManager, theme: PresentationThemeReference, color: PresentationThemeAccentColor?, wallpaper: TelegramWallpaper? = nil) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { +public func themeIconImage(account: Account, accountManager: AccountManager, theme: PresentationThemeReference, color: PresentationThemeAccentColor?, wallpaper: TelegramWallpaper? = nil) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { let colorsSignal: Signal<((UIColor, UIColor?, [UInt32]), [UIColor], [UIColor], UIImage?, Int32?), NoError> var reference: MediaResourceReference? @@ -1490,7 +1490,7 @@ public func themeIconImage(account: Account, accountManager: AccountManager, the } } -public func wallpaperThumbnail(account: Account, accountManager: AccountManager, fileReference: FileMediaReference, wallpaper: TelegramWallpaper, synchronousLoad: Bool) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { +public func wallpaperThumbnail(account: Account, accountManager: AccountManager, fileReference: FileMediaReference, wallpaper: TelegramWallpaper, synchronousLoad: Bool) -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> { switch wallpaper { case let .file(file): guard let thumbnail = smallestImageRepresentation(file.file.previewRepresentations) else {