diff --git a/submodules/ChatListUI/Sources/Node/ChatListNode.swift b/submodules/ChatListUI/Sources/Node/ChatListNode.swift index 0a8889f411..6121b32cb9 100644 --- a/submodules/ChatListUI/Sources/Node/ChatListNode.swift +++ b/submodules/ChatListUI/Sources/Node/ChatListNode.swift @@ -815,7 +815,7 @@ public final class ChatListNode: ListView { if Namespaces.PeerGroup.archive == groupId { displayArchiveIntro = context.sharedContext.accountManager.noticeEntry(key: ApplicationSpecificNotice.archiveIntroDismissedKey()) |> map { entry -> Bool in - if let value = entry.value as? ApplicationSpecificVariantNotice { + if let value = entry.value?.get(ApplicationSpecificVariantNotice.self) { return !value.value } else { return true diff --git a/submodules/InstantPageCache/Sources/CachedInstantPages.swift b/submodules/InstantPageCache/Sources/CachedInstantPages.swift index 8b528633c6..569d02f99e 100644 --- a/submodules/InstantPageCache/Sources/CachedInstantPages.swift +++ b/submodules/InstantPageCache/Sources/CachedInstantPages.swift @@ -6,7 +6,7 @@ import TelegramCore import TelegramUIPreferences import PersistentStringHash -public final class CachedInstantPage: PostboxCoding { +public final class CachedInstantPage: Codable { public let webPage: TelegramMediaWebpage public let timestamp: Int32 @@ -15,14 +15,20 @@ public final class CachedInstantPage: PostboxCoding { self.timestamp = timestamp } - public init(decoder: PostboxDecoder) { - self.webPage = decoder.decodeObjectForKey("webpage", decoder: { TelegramMediaWebpage(decoder: $0) }) as! TelegramMediaWebpage - self.timestamp = decoder.decodeInt32ForKey("timestamp", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let webPageData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "webpage") + self.webPage = TelegramMediaWebpage(decoder: PostboxDecoder(buffer: MemoryBuffer(data: webPageData.data))) + + self.timestamp = try container.decode(Int32.self, forKey: "timestamp") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.webPage, forKey: "webpage") - encoder.encodeInt32(self.timestamp, forKey: "timestamp") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(PostboxEncoder().encodeObjectToRawData(self.webPage), forKey: "webpage") + try container.encode(self.timestamp, forKey: "timestamp") } } @@ -30,7 +36,7 @@ public func cachedInstantPage(postbox: Postbox, url: String) -> Signal CachedInstantPage? in let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: url.persistentHashValue)) - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedInstantPages, key: key)) as? CachedInstantPage { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedInstantPages, key: key))?.get(CachedInstantPage.self) { return entry } else { return nil @@ -45,8 +51,8 @@ public func updateCachedInstantPage(postbox: Postbox, url: String, webPage: Tele let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: url.persistentHashValue)) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedInstantPages, key: key) - if let webPage = webPage { - transaction.putItemCacheEntry(id: id, entry: CachedInstantPage(webPage: webPage, timestamp: Int32(CFAbsoluteTimeGetCurrent())), collectionSpec: collectionSpec) + if let webPage = webPage, let entry = CodableEntry(CachedInstantPage(webPage: webPage, timestamp: Int32(CFAbsoluteTimeGetCurrent()))) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) } else { transaction.removeItemCacheEntry(id: id) } diff --git a/submodules/InstantPageUI/Sources/InstantPageStoredState.swift b/submodules/InstantPageUI/Sources/InstantPageStoredState.swift index 3334d421cb..992f9e55f0 100644 --- a/submodules/InstantPageUI/Sources/InstantPageStoredState.swift +++ b/submodules/InstantPageUI/Sources/InstantPageStoredState.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore import TelegramUIPreferences -public final class InstantPageStoredDetailsState: PostboxCoding { +public final class InstantPageStoredDetailsState: Codable { public let index: Int32 public let expanded: Bool public let details: [InstantPageStoredDetailsState] @@ -16,20 +16,24 @@ public final class InstantPageStoredDetailsState: PostboxCoding { self.details = details } - public init(decoder: PostboxDecoder) { - self.index = decoder.decodeInt32ForKey("index", orElse: 0) - self.expanded = decoder.decodeBoolForKey("expanded", orElse: false) - self.details = decoder.decodeObjectArrayForKey("details") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.index = try container.decode(Int32.self, forKey: "index") + self.expanded = try container.decode(Bool.self, forKey: "expanded") + self.details = try container.decode([InstantPageStoredDetailsState].self, forKey: "details") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.index, forKey: "index") - encoder.encodeBool(self.expanded, forKey: "expanded") - encoder.encodeObjectArray(self.details, forKey: "details") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.index, forKey: "index") + try container.encode(self.expanded, forKey: "expanded") + try container.encode(self.details, forKey: "details") } } -public final class InstantPageStoredState: PostboxCoding { +public final class InstantPageStoredState: Codable { public let contentOffset: Double public let details: [InstantPageStoredDetailsState] @@ -38,14 +42,18 @@ public final class InstantPageStoredState: PostboxCoding { self.details = details } - public init(decoder: PostboxDecoder) { - self.contentOffset = decoder.decodeDoubleForKey("offset", orElse: 0.0) - self.details = decoder.decodeObjectArrayForKey("details") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.contentOffset = try container.decode(Double.self, forKey: "offset") + self.details = try container.decode([InstantPageStoredDetailsState].self, forKey: "details") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeDouble(self.contentOffset, forKey: "offset") - encoder.encodeObjectArray(self.details, forKey: "details") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.contentOffset, forKey: "offset") + try container.encode(self.details, forKey: "details") } } @@ -53,7 +61,7 @@ public func instantPageStoredState(postbox: Postbox, webPage: TelegramMediaWebpa return postbox.transaction { transaction -> InstantPageStoredState? in let key = ValueBoxKey(length: 8) key.setInt64(0, value: webPage.webpageId.id) - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.instantPageStoredState, key: key)) as? InstantPageStoredState { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.instantPageStoredState, key: key))?.get(InstantPageStoredState.self) { return entry } else { return nil @@ -68,8 +76,8 @@ public func updateInstantPageStoredStateInteractively(postbox: Postbox, webPage: let key = ValueBoxKey(length: 8) key.setInt64(0, value: webPage.webpageId.id) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.instantPageStoredState, key: key) - if let state = state { - transaction.putItemCacheEntry(id: id, entry: state, collectionSpec: collectionSpec) + if let state = state, let entry = CodableEntry(state) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) } else { transaction.removeItemCacheEntry(id: id) } diff --git a/submodules/LocationUI/Sources/CachedGeocodes.swift b/submodules/LocationUI/Sources/CachedGeocodes.swift index bb2f6e9267..5b76e80543 100644 --- a/submodules/LocationUI/Sources/CachedGeocodes.swift +++ b/submodules/LocationUI/Sources/CachedGeocodes.swift @@ -8,7 +8,7 @@ import PersistentStringHash import AccountContext import Geocoding -public final class CachedGeocode: PostboxCoding { +public final class CachedGeocode: Codable { public let latitude: Double public let longitude: Double @@ -17,14 +17,18 @@ public final class CachedGeocode: PostboxCoding { self.longitude = longitude } - public init(decoder: PostboxDecoder) { - self.latitude = decoder.decodeDoubleForKey("lat", orElse: 0.0) - self.longitude = decoder.decodeDoubleForKey("lon", orElse: 0.0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.latitude = try container.decode(Double.self, forKey: "lat") + self.longitude = try container.decode(Double.self, forKey: "lon") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeDouble(self.latitude, forKey: "lat") - encoder.encodeDouble(self.longitude, forKey: "lon") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.latitude, forKey: "lat") + try container.encode(self.longitude, forKey: "lon") } } @@ -32,7 +36,7 @@ private func cachedGeocode(postbox: Postbox, address: DeviceContactAddressData) return postbox.transaction { transaction -> CachedGeocode? in let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: address.string.persistentHashValue)) - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedGeocodes, key: key)) as? CachedGeocode { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedGeocodes, key: key))?.get(CachedGeocode.self) { return entry } else { return nil @@ -47,7 +51,9 @@ private func updateCachedGeocode(postbox: Postbox, address: DeviceContactAddress let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: address.string.persistentHashValue)) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedGeocodes, key: key) - transaction.putItemCacheEntry(id: id, entry: CachedGeocode(latitude: latitude, longitude: longitude), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedGeocode(latitude: latitude, longitude: longitude)) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) + } return (latitude, longitude) } } diff --git a/submodules/MediaResources/Sources/MediaPlaybackStoredState.swift b/submodules/MediaResources/Sources/MediaPlaybackStoredState.swift index c3fb8009c6..372b7eb347 100644 --- a/submodules/MediaResources/Sources/MediaPlaybackStoredState.swift +++ b/submodules/MediaResources/Sources/MediaPlaybackStoredState.swift @@ -5,7 +5,7 @@ import Postbox import TelegramCore import TelegramUIPreferences -public final class MediaPlaybackStoredState: PostboxCoding { +public final class MediaPlaybackStoredState: Codable { public let timestamp: Double public let playbackRate: AudioPlaybackRate @@ -14,14 +14,18 @@ public final class MediaPlaybackStoredState: PostboxCoding { self.playbackRate = playbackRate } - public init(decoder: PostboxDecoder) { - self.timestamp = decoder.decodeDoubleForKey("timestamp", orElse: 0.0) - self.playbackRate = AudioPlaybackRate(rawValue: decoder.decodeInt32ForKey("playbackRate", orElse: AudioPlaybackRate.x1.rawValue)) ?? .x1 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.timestamp = try container.decode(Double.self, forKey: "timestamp") + self.playbackRate = AudioPlaybackRate(rawValue: try container.decode(Int32.self, forKey: "playbackRate")) ?? .x1 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeDouble(self.timestamp, forKey: "timestamp") - encoder.encodeInt32(self.playbackRate.rawValue, forKey: "playbackRate") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.timestamp, forKey: "timestamp") + try container.encode(self.playbackRate.rawValue, forKey: "playbackRate") } } @@ -30,7 +34,7 @@ public func mediaPlaybackStoredState(postbox: Postbox, messageId: MessageId) -> let key = ValueBoxKey(length: 8) key.setInt32(0, value: messageId.namespace) key.setInt32(4, value: messageId.id) - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.mediaPlaybackStoredState, key: key)) as? MediaPlaybackStoredState { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.mediaPlaybackStoredState, key: key))?.get(MediaPlaybackStoredState.self) { return entry } else { return nil @@ -46,8 +50,8 @@ public func updateMediaPlaybackStoredStateInteractively(postbox: Postbox, messag key.setInt32(0, value: messageId.namespace) key.setInt32(4, value: messageId.id) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.mediaPlaybackStoredState, key: key) - if let state = state { - transaction.putItemCacheEntry(id: id, entry: state, collectionSpec: collectionSpec) + if let state = state, let entry = CodableEntry(state) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) } else { transaction.removeItemCacheEntry(id: id) } diff --git a/submodules/Postbox/Sources/AccountManager.swift b/submodules/Postbox/Sources/AccountManager.swift index 3cdd47d984..520560921a 100644 --- a/submodules/Postbox/Sources/AccountManager.swift +++ b/submodules/Postbox/Sources/AccountManager.swift @@ -20,8 +20,8 @@ public struct AccountManagerModifier { public let setAccessChallengeData: (PostboxAccessChallengeData) -> Void public let getVersion: () -> Int32? public let setVersion: (Int32) -> Void - public let getNotice: (NoticeEntryKey) -> NoticeEntry? - public let setNotice: (NoticeEntryKey, NoticeEntry?) -> Void + public let getNotice: (NoticeEntryKey) -> CodableEntry? + public let setNotice: (NoticeEntryKey, CodableEntry?) -> Void public let clearNotices: () -> Void } diff --git a/submodules/Postbox/Sources/AdditionalMessageHistoryViewData.swift b/submodules/Postbox/Sources/AdditionalMessageHistoryViewData.swift index 357cf6ce5c..9cf5cb60e6 100644 --- a/submodules/Postbox/Sources/AdditionalMessageHistoryViewData.swift +++ b/submodules/Postbox/Sources/AdditionalMessageHistoryViewData.swift @@ -19,7 +19,7 @@ public enum AdditionalMessageHistoryViewDataEntry { case peerChatState(PeerId, PeerChatState?) case totalUnreadState(ChatListTotalUnreadState) case peerNotificationSettings(PeerNotificationSettings?) - case cacheEntry(ItemCacheEntryId, PostboxCoding?) + case cacheEntry(ItemCacheEntryId, CodableEntry?) case preferencesEntry(ValueBoxKey, PreferencesEntry?) case peerIsContact(PeerId, Bool) case peer(PeerId, Peer?) diff --git a/submodules/Postbox/Sources/CachedItemView.swift b/submodules/Postbox/Sources/CachedItemView.swift index b1048fd3a6..2a6d676eb2 100644 --- a/submodules/Postbox/Sources/CachedItemView.swift +++ b/submodules/Postbox/Sources/CachedItemView.swift @@ -2,7 +2,7 @@ import Foundation final class MutableCachedItemView: MutablePostboxView { private let id: ItemCacheEntryId - fileprivate var value: PostboxCoding? + fileprivate var value: CodableEntry? init(postbox: Postbox, id: ItemCacheEntryId) { self.id = id @@ -23,7 +23,7 @@ final class MutableCachedItemView: MutablePostboxView { } public final class CachedItemView: PostboxView { - public let value: PostboxCoding? + public let value: CodableEntry? init(_ view: MutableCachedItemView) { self.value = view.value diff --git a/submodules/Postbox/Sources/ItemCacheTable.swift b/submodules/Postbox/Sources/ItemCacheTable.swift index cb59ab21fe..9fc7de9f06 100644 --- a/submodules/Postbox/Sources/ItemCacheTable.swift +++ b/submodules/Postbox/Sources/ItemCacheTable.swift @@ -64,29 +64,14 @@ final class ItemCacheTable: Table { key.setInt32(2, value: index) return key } - - func put(id: ItemCacheEntryId, entry: PostboxCoding, metaTable: ItemCacheMetaTable) { - let encoder = PostboxEncoder() - encoder.encodeRootObject(entry) - withExtendedLifetime(encoder, { - self.valueBox.set(self.table, key: self.itemKey(id: id), value: encoder.readBufferNoCopy()) - }) + + func put(id: ItemCacheEntryId, entry: CodableEntry, metaTable: ItemCacheMetaTable) { + self.valueBox.set(self.table, key: self.itemKey(id: id), value: ReadBuffer(data: entry.data)) } - func putData(id: ItemCacheEntryId, entry: Data, metaTable: ItemCacheMetaTable) { - self.valueBox.set(self.table, key: self.itemKey(id: id), value: ReadBuffer(data: entry)) - } - - func retrieve(id: ItemCacheEntryId, metaTable: ItemCacheMetaTable) -> PostboxCoding? { - if let value = self.valueBox.get(self.table, key: self.itemKey(id: id)), let entry = PostboxDecoder(buffer: value).decodeRootObject() { - return entry - } - return nil - } - - func retrieveData(id: ItemCacheEntryId, metaTable: ItemCacheMetaTable) -> Data? { + func retrieve(id: ItemCacheEntryId, metaTable: ItemCacheMetaTable) -> CodableEntry? { if let value = self.valueBox.get(self.table, key: self.itemKey(id: id)) { - return value.makeData() + return CodableEntry(data: value.makeData()) } return nil } diff --git a/submodules/Postbox/Sources/NoticeEntryView.swift b/submodules/Postbox/Sources/NoticeEntryView.swift index 99c5c84560..bdbd8ad107 100644 --- a/submodules/Postbox/Sources/NoticeEntryView.swift +++ b/submodules/Postbox/Sources/NoticeEntryView.swift @@ -2,7 +2,7 @@ import Foundation final class MutableNoticeEntryView { private let key: NoticeEntryKey - fileprivate var value: NoticeEntry? + fileprivate var value: CodableEntry? init(accountManagerImpl: AccountManagerImpl, key: NoticeEntryKey) { self.key = key @@ -23,7 +23,7 @@ final class MutableNoticeEntryView { } public final class NoticeEntryView { - public let value: NoticeEntry? + public let value: CodableEntry? init(_ view: MutableNoticeEntryView) { self.value = view.value diff --git a/submodules/Postbox/Sources/NoticeTable.swift b/submodules/Postbox/Sources/NoticeTable.swift index 8b9fb22e6d..5c8f7b39d0 100644 --- a/submodules/Postbox/Sources/NoticeTable.swift +++ b/submodules/Postbox/Sources/NoticeTable.swift @@ -26,11 +26,7 @@ public struct NoticeEntryKey: Hashable { } private struct CachedEntry { - let entry: NoticeEntry? -} - -public protocol NoticeEntry: PostboxCoding { - func isEqual(to: NoticeEntry) -> Bool + let entry: CodableEntry? } final class NoticeTable: Table { @@ -41,22 +37,22 @@ final class NoticeTable: Table { return ValueBoxTable(id: id, keyType: .binary, compactValuesOnCreation: true) } - func getAll() -> [ValueBoxKey: NoticeEntry] { - var result: [ValueBoxKey: NoticeEntry] = [:] + func getAll() -> [ValueBoxKey: CodableEntry] { + var result: [ValueBoxKey: CodableEntry] = [:] self.valueBox.scan(self.table, values: { key, value in - if let object = PostboxDecoder(buffer: value).decodeRootObject() as? NoticeEntry { - result[key] = object - } + let object = CodableEntry(data: value.makeData()) + result[key] = object return true }) return result } - func get(key: NoticeEntryKey) -> NoticeEntry? { + func get(key: NoticeEntryKey) -> CodableEntry? { if let cached = self.cachedEntries[key] { return cached.entry } else { - if let value = self.valueBox.get(self.table, key: key.combinedKey), let object = PostboxDecoder(buffer: value).decodeRootObject() as? NoticeEntry { + if let value = self.valueBox.get(self.table, key: key.combinedKey) { + let object = CodableEntry(data: value.makeData()) self.cachedEntries[key] = CachedEntry(entry: object) return object } else { @@ -66,7 +62,7 @@ final class NoticeTable: Table { } } - func set(key: NoticeEntryKey, value: NoticeEntry?) { + func set(key: NoticeEntryKey, value: CodableEntry?) { self.cachedEntries[key] = CachedEntry(entry: value) updatedEntryKeys.insert(key) } @@ -92,11 +88,7 @@ final class NoticeTable: Table { if !self.updatedEntryKeys.isEmpty { for key in self.updatedEntryKeys { if let value = self.cachedEntries[key]?.entry { - let encoder = PostboxEncoder() - encoder.encodeRootObject(value) - withExtendedLifetime(encoder, { - self.valueBox.set(self.table, key: key.combinedKey, value: encoder.readBufferNoCopy()) - }) + self.valueBox.set(self.table, key: key.combinedKey, value: ReadBuffer(data: value.data)) } else { self.valueBox.remove(self.table, key: key.combinedKey, secure: false) } diff --git a/submodules/Postbox/Sources/Postbox.swift b/submodules/Postbox/Sources/Postbox.swift index 605c4a4fae..d9f7a4cab6 100644 --- a/submodules/Postbox/Sources/Postbox.swift +++ b/submodules/Postbox/Sources/Postbox.swift @@ -712,30 +712,20 @@ public final class Transaction { return self.postbox?.storedMessageId(peerId: peerId, namespace: namespace, timestamp: timestamp) } - public func putItemCacheEntry(id: ItemCacheEntryId, entry: PostboxCoding, collectionSpec: ItemCacheCollectionSpec) { + public func putItemCacheEntry(id: ItemCacheEntryId, entry: CodableEntry, collectionSpec: ItemCacheCollectionSpec) { assert(!self.disposed) self.postbox?.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) } - - public func putItemCacheEntryData(id: ItemCacheEntryId, entry: Data, collectionSpec: ItemCacheCollectionSpec) { - assert(!self.disposed) - self.postbox?.putItemCacheEntryData(id: id, entry: entry, collectionSpec: collectionSpec) - } public func removeItemCacheEntry(id: ItemCacheEntryId) { assert(!self.disposed) self.postbox?.removeItemCacheEntry(id: id) } - public func retrieveItemCacheEntry(id: ItemCacheEntryId) -> PostboxCoding? { + public func retrieveItemCacheEntry(id: ItemCacheEntryId) -> CodableEntry? { assert(!self.disposed) return self.postbox?.retrieveItemCacheEntry(id: id) } - - public func retrieveItemCacheEntryData(id: ItemCacheEntryId) -> Data? { - assert(!self.disposed) - return self.postbox?.retrieveItemCacheEntryData(id: id) - } public func clearItemCacheCollection(collectionId: ItemCacheCollectionId) { assert(!self.disposed) @@ -942,7 +932,7 @@ public final class Transaction { } } - public func getAllNoticeEntries() -> [ValueBoxKey: NoticeEntry] { + public func getAllNoticeEntries() -> [ValueBoxKey: CodableEntry] { assert(!self.disposed) if let postbox = self.postbox { return postbox.noticeTable.getAll() @@ -951,7 +941,7 @@ public final class Transaction { } } - public func getNoticeEntry(key: NoticeEntryKey) -> PostboxCoding? { + public func getNoticeEntry(key: NoticeEntryKey) -> CodableEntry? { assert(!self.disposed) if let postbox = self.postbox { return postbox.noticeTable.get(key: key) @@ -960,7 +950,7 @@ public final class Transaction { } } - public func setNoticeEntry(key: NoticeEntryKey, value: NoticeEntry?) { + public func setNoticeEntry(key: NoticeEntryKey, value: CodableEntry?) { assert(!self.disposed) self.postbox?.setNoticeEntry(key: key, value: value) } @@ -2347,23 +2337,14 @@ public final class Postbox { } } - fileprivate func putItemCacheEntry(id: ItemCacheEntryId, entry: PostboxCoding, collectionSpec: ItemCacheCollectionSpec) { + fileprivate func putItemCacheEntry(id: ItemCacheEntryId, entry: CodableEntry, collectionSpec: ItemCacheCollectionSpec) { self.itemCacheTable.put(id: id, entry: entry, metaTable: self.itemCacheMetaTable) self.currentUpdatedCacheEntryKeys.insert(id) } - - fileprivate func putItemCacheEntryData(id: ItemCacheEntryId, entry: Data, collectionSpec: ItemCacheCollectionSpec) { - self.itemCacheTable.putData(id: id, entry: entry, metaTable: self.itemCacheMetaTable) - self.currentUpdatedCacheEntryKeys.insert(id) - } - func retrieveItemCacheEntry(id: ItemCacheEntryId) -> PostboxCoding? { + func retrieveItemCacheEntry(id: ItemCacheEntryId) -> CodableEntry? { return self.itemCacheTable.retrieve(id: id, metaTable: self.itemCacheMetaTable) } - - func retrieveItemCacheEntryData(id: ItemCacheEntryId) -> Data? { - return self.itemCacheTable.retrieveData(id: id, metaTable: self.itemCacheMetaTable) - } func clearItemCacheCollection(collectionId: ItemCacheCollectionId) { return self.itemCacheTable.removeAll(collectionId: collectionId) @@ -2400,11 +2381,11 @@ public final class Postbox { } } - fileprivate func setNoticeEntry(key: NoticeEntryKey, value: NoticeEntry?) { + fileprivate func setNoticeEntry(key: NoticeEntryKey, value: CodableEntry?) { let current = self.noticeTable.get(key: key) let updated: Bool if let current = current, let value = value { - updated = !current.isEqual(to: value) + updated = current.data != value.data } else if (current != nil) != (value != nil) { updated = true } else { diff --git a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift index c9dc3ce412..365aa0e83d 100644 --- a/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift +++ b/submodules/Postbox/Sources/Utils/Encoder/AdaptedPostboxUnkeyedEncodingContainer.swift @@ -120,6 +120,18 @@ extension _AdaptedPostboxEncoder.UnkeyedContainer: UnkeyedEncodingContainer { try self.encode(value as! String) } else if value is Data { try self.encode(value as! Data) + } else if let value = value as? AdaptedPostboxEncoder.RawObjectData { + let buffer = WriteBuffer() + + var typeHash: Int32 = value.typeHash + buffer.write(&typeHash, offset: 0, length: 4) + + var length: Int32 = Int32(value.data.count) + buffer.write(&length, offset: 0, length: 4) + + buffer.write(value.data) + + self.items.append(.object(buffer.makeData())) } else { let typeHash: Int32 = murMurHashString32("\(type(of: value))") diff --git a/submodules/TelegramCore/Sources/Account/AccountManager.swift b/submodules/TelegramCore/Sources/Account/AccountManager.swift index 6c36ccaab2..4fa3e0ed8e 100644 --- a/submodules/TelegramCore/Sources/Account/AccountManager.swift +++ b/submodules/TelegramCore/Sources/Account/AccountManager.swift @@ -116,7 +116,6 @@ private var declaredEncodables: Void = { declareEncodable(SourceReferenceMessageAttribute.self, f: { SourceReferenceMessageAttribute(decoder: $0) }) declareEncodable(EditedMessageAttribute.self, f: { EditedMessageAttribute(decoder: $0) }) declareEncodable(ReplyMarkupMessageAttribute.self, f: { ReplyMarkupMessageAttribute(decoder: $0) }) - declareEncodable(CachedResolvedByNamePeer.self, f: { CachedResolvedByNamePeer(decoder: $0) }) declareEncodable(OutgoingChatContextResultMessageAttribute.self, f: { OutgoingChatContextResultMessageAttribute(decoder: $0) }) declareEncodable(HttpReferenceMediaResource.self, f: { HttpReferenceMediaResource(decoder: $0) }) declareEncodable(WebFileReferenceMediaResource.self, f: { WebFileReferenceMediaResource(decoder: $0) }) @@ -151,51 +150,24 @@ private var declaredEncodables: Void = { declareEncodable(SynchronizeSavedGifsOperation.self, f: { SynchronizeSavedGifsOperation(decoder: $0) }) declareEncodable(SynchronizeSavedStickersOperation.self, f: { SynchronizeSavedStickersOperation(decoder: $0) }) declareEncodable(SynchronizeRecentlyUsedMediaOperation.self, f: { SynchronizeRecentlyUsedMediaOperation(decoder: $0) }) - /*declareEncodable(CacheStorageSettings.self, f: { CacheStorageSettings(decoder: $0) }) - declareEncodable(LocalizationSettings.self, f: { LocalizationSettings(decoder: $0) }) - declareEncodable(LocalizationListState.self, f: { LocalizationListState(decoder: $0) }) - declareEncodable(ProxySettings.self, f: { ProxySettings(decoder: $0) }) - declareEncodable(NetworkSettings.self, f: { NetworkSettings(decoder: $0) }) - declareEncodable(RemoteStorageConfiguration.self, f: { RemoteStorageConfiguration(decoder: $0) }) - declareEncodable(LimitsConfiguration.self, f: { LimitsConfiguration(decoder: $0) }) - declareEncodable(VoipConfiguration.self, f: { VoipConfiguration(decoder: $0) }) - declareEncodable(SuggestedLocalizationEntry.self, f: { SuggestedLocalizationEntry(decoder: $0) })*/ declareEncodable(SynchronizeLocalizationUpdatesOperation.self, f: { SynchronizeLocalizationUpdatesOperation(decoder: $0) }) declareEncodable(ChannelMessageStateVersionAttribute.self, f: { ChannelMessageStateVersionAttribute(decoder: $0) }) declareEncodable(PeerGroupMessageStateVersionAttribute.self, f: { PeerGroupMessageStateVersionAttribute(decoder: $0) }) declareEncodable(CachedSecretChatData.self, f: { CachedSecretChatData(decoder: $0) }) - declareEncodable(TemporaryTwoStepPasswordToken.self, f: { TemporaryTwoStepPasswordToken(decoder: $0) }) declareEncodable(AuthorSignatureMessageAttribute.self, f: { AuthorSignatureMessageAttribute(decoder: $0) }) declareEncodable(TelegramMediaExpiredContent.self, f: { TelegramMediaExpiredContent(decoder: $0) }) declareEncodable(SavedStickerItem.self, f: { SavedStickerItem(decoder: $0) }) declareEncodable(ConsumablePersonalMentionMessageAttribute.self, f: { ConsumablePersonalMentionMessageAttribute(decoder: $0) }) declareEncodable(ConsumePersonalMessageAction.self, f: { ConsumePersonalMessageAction(decoder: $0) }) - declareEncodable(CachedStickerPack.self, f: { CachedStickerPack(decoder: $0) }) - //declareEncodable(LoggingSettings.self, f: { LoggingSettings(decoder: $0) }) - declareEncodable(CachedLocalizationInfos.self, f: { CachedLocalizationInfos(decoder: $0) }) - declareEncodable(CachedSecureIdConfiguration.self, f: { CachedSecureIdConfiguration(decoder: $0) }) - declareEncodable(CachedWallpapersConfiguration.self, f: { CachedWallpapersConfiguration(decoder: $0) }) - declareEncodable(CachedThemesConfiguration.self, f: { CachedThemesConfiguration(decoder: $0) }) declareEncodable(SynchronizeGroupedPeersOperation.self, f: { SynchronizeGroupedPeersOperation(decoder: $0) }) - //declareEncodable(ContentPrivacySettings.self, f: { ContentPrivacySettings(decoder: $0) }) declareEncodable(TelegramDeviceContactImportedData.self, f: { TelegramDeviceContactImportedData(decoder: $0) }) declareEncodable(SecureFileMediaResource.self, f: { SecureFileMediaResource(decoder: $0) }) - declareEncodable(CachedStickerQueryResult.self, f: { CachedStickerQueryResult(decoder: $0) }) declareEncodable(TelegramWallpaper.self, f: { TelegramWallpaper(decoder: $0) }) declareEncodable(TelegramTheme.self, f: { TelegramTheme(decoder: $0) }) - //declareEncodable(ThemeSettings.self, f: { ThemeSettings(decoder: $0) }) declareEncodable(SynchronizeMarkAllUnseenPersonalMessagesOperation.self, f: { SynchronizeMarkAllUnseenPersonalMessagesOperation(decoder: $0) }) declareEncodable(SynchronizeAppLogEventsOperation.self, f: { SynchronizeAppLogEventsOperation(decoder: $0) }) - declareEncodable(CachedRecentPeers.self, f: { CachedRecentPeers(decoder: $0) }) - //declareEncodable(AppChangelogState.self, f: { AppChangelogState(decoder: $0) }) - //declareEncodable(AppConfiguration.self, f: { AppConfiguration(decoder: $0) }) - //declareEncodable(JSON.self, f: { JSON(decoder: $0) }) - //declareEncodable(SearchBotsConfiguration.self, f: { SearchBotsConfiguration(decoder: $0) }) - //declareEncodable(AutodownloadSettings.self, f: { AutodownloadSettings(decoder: $0 )}) declareEncodable(TelegramMediaPoll.self, f: { TelegramMediaPoll(decoder: $0) }) declareEncodable(TelegramMediaUnsupported.self, f: { TelegramMediaUnsupported(decoder: $0) }) - //declareEncodable(ContactsSettings.self, f: { ContactsSettings(decoder: $0) }) - //declareEncodable(SecretChatSettings.self, f: { SecretChatSettings(decoder: $0) }) declareEncodable(EmojiKeywordCollectionInfo.self, f: { EmojiKeywordCollectionInfo(decoder: $0) }) declareEncodable(EmojiKeywordItem.self, f: { EmojiKeywordItem(decoder: $0) }) declareEncodable(SynchronizeEmojiKeywordsOperation.self, f: { SynchronizeEmojiKeywordsOperation(decoder: $0) }) @@ -209,34 +181,18 @@ private var declaredEncodables: Void = { declareEncodable(UpdateMessageReactionsAction.self, f: { UpdateMessageReactionsAction(decoder: $0) }) declareEncodable(RestrictedContentMessageAttribute.self, f: { RestrictedContentMessageAttribute(decoder: $0) }) declareEncodable(SendScheduledMessageImmediatelyAction.self, f: { SendScheduledMessageImmediatelyAction(decoder: $0) }) - //declareEncodable(WalletCollection.self, f: { WalletCollection(decoder: $0) }) declareEncodable(EmbeddedMediaStickersMessageAttribute.self, f: { EmbeddedMediaStickersMessageAttribute(decoder: $0) }) declareEncodable(TelegramMediaWebpageAttribute.self, f: { TelegramMediaWebpageAttribute(decoder: $0) }) - declareEncodable(CachedPollOptionResult.self, f: { CachedPollOptionResult(decoder: $0) }) - //declareEncodable(ChatListFiltersState.self, f: { ChatListFiltersState(decoder: $0) }) - //declareEncodable(PeersNearbyState.self, f: { PeersNearbyState(decoder: $0) }) declareEncodable(TelegramMediaDice.self, f: { TelegramMediaDice(decoder: $0) }) - //declareEncodable(ChatListFiltersFeaturedState.self, f: { ChatListFiltersFeaturedState(decoder: $0) }) declareEncodable(SynchronizeChatListFiltersOperation.self, f: { SynchronizeChatListFiltersOperation(decoder: $0) }) declareEncodable(PromoChatListItem.self, f: { PromoChatListItem(decoder: $0) }) declareEncodable(TelegramMediaFile.VideoThumbnail.self, f: { TelegramMediaFile.VideoThumbnail(decoder: $0) }) - declareEncodable(CachedChatContextResult.self, f: { CachedChatContextResult(decoder: $0) }) declareEncodable(PeerAccessRestrictionInfo.self, f: { PeerAccessRestrictionInfo(decoder: $0) }) declareEncodable(TelegramMediaImage.VideoRepresentation.self, f: { TelegramMediaImage.VideoRepresentation(decoder: $0) }) - //declareEncodable(Country.self, f: { Country(decoder: $0) }) - //declareEncodable(Country.CountryCode.self, f: { Country.CountryCode(decoder: $0) }) - //declareEncodable(CountriesList.self, f: { CountriesList(decoder: $0) }) declareEncodable(ValidationMessageAttribute.self, f: { ValidationMessageAttribute(decoder: $0) }) declareEncodable(EmojiSearchQueryMessageAttribute.self, f: { EmojiSearchQueryMessageAttribute(decoder: $0) }) - declareEncodable(CachedPeerInvitationImporters.self, f: { CachedPeerInvitationImporters(decoder: $0) }) - declareEncodable(CachedPeerExportedInvitations.self, f: { CachedPeerExportedInvitations(decoder: $0) }) - declareEncodable(ExportedInvitation.self, f: { ExportedInvitation(decoder: $0) }) - declareEncodable(CachedDisplayAsPeers.self, f: { CachedDisplayAsPeers(decoder: $0) }) - //declareEncodable(WallpapersState.self, f: { WallpapersState(decoder: $0) }) declareEncodable(WallpaperDataResource.self, f: { WallpaperDataResource(decoder: $0) }) declareEncodable(ForwardOptionsMessageAttribute.self, f: { ForwardOptionsMessageAttribute(decoder: $0) }) - //declareEncodable(ChatTheme.self, f: { ChatTheme(decoder: $0) }) - //declareEncodable(ChatThemes.self, f: { ChatThemes(decoder: $0) }) return }() diff --git a/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift b/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift index d7af4e5d03..307a8f24e0 100644 --- a/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift +++ b/submodules/TelegramCore/Sources/State/CachedSentMediaReferences.swift @@ -32,11 +32,12 @@ enum CachedSentMediaReferenceKey { } func cachedSentMediaReference(postbox: Postbox, key: CachedSentMediaReferenceKey) -> Signal { - return postbox.transaction { transaction -> Media? in + return .single(nil) + /*return postbox.transaction { transaction -> Media? in return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key)) as? Media - } + }*/ } func storeCachedSentMediaReference(transaction: Transaction, key: CachedSentMediaReferenceKey, media: Media) { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key), entry: media, collectionSpec: cachedSentMediaCollectionSpec) + //transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSentMediaReferences, key: key.key), entry: media, collectionSpec: cachedSentMediaCollectionSpec) } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedChannelData.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedChannelData.swift index 8616c3980a..e3da6270b9 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedChannelData.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedChannelData.swift @@ -413,7 +413,7 @@ public final class CachedChannelData: CachedPeerData { self.flags = CachedChannelFlags(rawValue: decoder.decodeInt32ForKey("f", orElse: 0)) self.about = decoder.decodeOptionalStringForKey("a") self.participantsSummary = CachedChannelParticipantsSummary(decoder: decoder) - self.exportedInvitation = decoder.decodeObjectForKey("i", decoder: { ExportedInvitation(decoder: $0) }) as? ExportedInvitation + self.exportedInvitation = decoder.decode(ExportedInvitation.self, forKey: "i") self.botInfos = decoder.decodeObjectArrayWithDecoderForKey("b") as [CachedPeerBotInfo] var peerIds = Set() @@ -515,7 +515,7 @@ public final class CachedChannelData: CachedPeerData { } self.participantsSummary.encode(encoder) if let exportedInvitation = self.exportedInvitation { - encoder.encodeObject(exportedInvitation, forKey: "i") + encoder.encode(exportedInvitation, forKey: "i") } else { encoder.encodeNil(forKey: "i") } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift index d05ae4fd76..624b1122a6 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedGroupData.swift @@ -118,7 +118,7 @@ public final class CachedGroupData: CachedPeerData { public init(decoder: PostboxDecoder) { let participants = decoder.decodeObjectForKey("p", decoder: { CachedGroupParticipants(decoder: $0) }) as? CachedGroupParticipants self.participants = participants - self.exportedInvitation = decoder.decodeObjectForKey("i", decoder: { ExportedInvitation(decoder: $0) }) as? ExportedInvitation + self.exportedInvitation = decoder.decode(ExportedInvitation.self, forKey: "i") self.botInfos = decoder.decodeObjectArrayWithDecoderForKey("b") as [CachedPeerBotInfo] if let legacyValue = decoder.decodeOptionalInt32ForKey("pcs") { self.peerStatusSettings = PeerStatusSettings(flags: PeerStatusSettings.Flags(rawValue: legacyValue), geoDistance: nil) @@ -181,7 +181,7 @@ public final class CachedGroupData: CachedPeerData { encoder.encodeNil(forKey: "p") } if let exportedInvitation = self.exportedInvitation { - encoder.encodeObject(exportedInvitation, forKey: "i") + encoder.encode(exportedInvitation, forKey: "i") } else { encoder.encodeNil(forKey: "i") } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedLocalizationInfos.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedLocalizationInfos.swift index 9026af12b2..c4e84b4ce9 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedLocalizationInfos.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedLocalizationInfos.swift @@ -1,17 +1,21 @@ import Postbox -public final class CachedLocalizationInfos: PostboxCoding { +public final class CachedLocalizationInfos: Codable { public let list: [LocalizationInfo] public init(list: [LocalizationInfo]) { self.list = list } - public init(decoder: PostboxDecoder) { - self.list = decoder.decodeObjectArrayWithDecoderForKey("l") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.list = try container.decode([LocalizationInfo].self, forKey: "t") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObjectArray(self.list, forKey: "l") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.list, forKey: "l") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedRecentPeers.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedRecentPeers.swift index 0ac338c6b6..bb750e0d49 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedRecentPeers.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedRecentPeers.swift @@ -1,6 +1,6 @@ import Postbox -public final class CachedRecentPeers: PostboxCoding { +public final class CachedRecentPeers: Codable { public let enabled: Bool public let ids: [PeerId] @@ -9,14 +9,18 @@ public final class CachedRecentPeers: PostboxCoding { self.ids = ids } - public init(decoder: PostboxDecoder) { - self.enabled = decoder.decodeInt32ForKey("enabled", orElse: 0) != 0 - self.ids = decoder.decodeInt64ArrayForKey("ids").map(PeerId.init) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.enabled = try container.decode(Int32.self, forKey: "enabled") != 0 + self.ids = (try container.decode([Int64].self, forKey: "ids")).map(PeerId.init) } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.enabled ? 1 : 0, forKey: "enabled") - encoder.encodeInt64Array(self.ids.map({ $0.toInt64() }), forKey: "ids") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.enabled ? 1 : 0) as Int32, forKey: "enabled") + try container.encode(self.ids.map({ $0.toInt64() }), forKey: "ids") } public static func cacheKey() -> ValueBoxKey { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift index 10d47173cb..2a9dab4083 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedResolvedByNamePeer.swift @@ -1,7 +1,7 @@ import Foundation import Postbox -public final class CachedResolvedByNamePeer: PostboxCoding { +public final class CachedResolvedByNamePeer: Codable { public let peerId: PeerId? public let timestamp: Int32 @@ -25,21 +25,17 @@ public final class CachedResolvedByNamePeer: PostboxCoding { self.timestamp = timestamp } - public init(decoder: PostboxDecoder) { - if let peerId = decoder.decodeOptionalInt64ForKey("p") { - self.peerId = PeerId(peerId) - } else { - self.peerId = nil - } - self.timestamp = decoder.decodeInt32ForKey("t", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.peerId = (try container.decodeIfPresent(Int64.self, forKey: "p")).flatMap(PeerId.init) + self.timestamp = try container.decode(Int32.self, forKey: "t") } - public func encode(_ encoder: PostboxEncoder) { - if let peerId = self.peerId { - encoder.encodeInt64(peerId.toInt64(), forKey: "p") - } else { - encoder.encodeNil(forKey: "p") - } - encoder.encodeInt32(self.timestamp, forKey: "t") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encodeIfPresent(self.peerId?.toInt64(), forKey: "p") + try container.encode(self.timestamp, forKey: "t") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedSecureIdConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedSecureIdConfiguration.swift index 8d8200bfb9..0dbd442908 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedSecureIdConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedSecureIdConfiguration.swift @@ -1,25 +1,29 @@ import Foundation import Postbox -public struct SecureIdConfiguration: PostboxCoding { +public struct SecureIdConfiguration: Codable { public let nativeLanguageByCountry: [String: String] public init(jsonString: String) { self.nativeLanguageByCountry = (try? JSONDecoder().decode(Dictionary.self, from: jsonString.data(using: .utf8) ?? Data())) ?? [:] } - public init(decoder: PostboxDecoder) { - let nativeLanguageByCountryData = decoder.decodeBytesForKey("nativeLanguageByCountry")! - self.nativeLanguageByCountry = (try? JSONDecoder().decode(Dictionary.self, from: nativeLanguageByCountryData.dataNoCopy())) ?? [:] + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let nativeLanguageByCountryData = try container.decode(Data.self, forKey: "nativeLanguageByCountry") + self.nativeLanguageByCountry = (try? JSONDecoder().decode(Dictionary.self, from: nativeLanguageByCountryData)) ?? [:] } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + let nativeLanguageByCountryData = (try? JSONEncoder().encode(self.nativeLanguageByCountry)) ?? Data() - encoder.encodeBytes(MemoryBuffer(data: nativeLanguageByCountryData), forKey: "nativeLanguageByCountry") + try container.encode(nativeLanguageByCountryData, forKey: "nativeLanguageByCountry") } } -public final class CachedSecureIdConfiguration: PostboxCoding { +public final class CachedSecureIdConfiguration: Codable { public let value: SecureIdConfiguration public let hash: Int32 @@ -28,13 +32,17 @@ public final class CachedSecureIdConfiguration: PostboxCoding { self.hash = hash } - public init(decoder: PostboxDecoder) { - self.value = decoder.decodeObjectForKey("value", decoder: { SecureIdConfiguration(decoder: $0) }) as! SecureIdConfiguration - self.hash = decoder.decodeInt32ForKey("hash", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.value = try container.decode(SecureIdConfiguration.self, forKey: "value") + self.hash = try container.decode(Int32.self, forKey: "hash") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.value, forKey: "value") - encoder.encodeInt32(self.hash, forKey: "hash") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.value, forKey: "value") + try container.encode(self.hash, forKey: "hash") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerPack.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerPack.swift index ea4f51d4e6..dd8774e9e3 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerPack.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerPack.swift @@ -1,6 +1,6 @@ import Postbox -public final class CachedStickerPack: PostboxCoding { +public final class CachedStickerPack: Codable { public let info: StickerPackCollectionInfo? public let items: [StickerPackItem] public let hash: Int32 @@ -11,20 +11,36 @@ public final class CachedStickerPack: PostboxCoding { self.hash = hash } - public init(decoder: PostboxDecoder) { - self.info = decoder.decodeObjectForKey("in", decoder: { StickerPackCollectionInfo(decoder: $0) }) as? StickerPackCollectionInfo - self.items = decoder.decodeObjectArrayForKey("it").map { $0 as! StickerPackItem } - self.hash = decoder.decodeInt32ForKey("h", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + if let infoData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "in") { + self.info = StickerPackCollectionInfo(decoder: PostboxDecoder(buffer: MemoryBuffer(data: infoData.data))) + } else { + self.info = nil + } + + self.items = (try container.decode([AdaptedPostboxDecoder.RawObjectData].self, forKey: "it")).map { itemData in + return StickerPackItem(decoder: PostboxDecoder(buffer: MemoryBuffer(data: itemData.data))) + } + + self.hash = try container.decode(Int32.self, forKey: "h") } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + if let info = self.info { - encoder.encodeObject(info, forKey: "in") + try container.encode(PostboxEncoder().encodeObjectToRawData(info), forKey: "in") } else { - encoder.encodeNil(forKey: "in") + try container.encodeNil(forKey: "in") } - encoder.encodeObjectArray(self.items, forKey: "it") - encoder.encodeInt32(self.hash, forKey: "h") + + try container.encode(self.items.map { item in + return PostboxEncoder().encodeObjectToRawData(item) + }, forKey: "it") + + try container.encode(self.hash, forKey: "h") } public static func cacheKey(_ id: ItemCollectionId) -> ValueBoxKey { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerQueryResult.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerQueryResult.swift index 7a0d7769ec..eeda71abff 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerQueryResult.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedStickerQueryResult.swift @@ -1,6 +1,6 @@ import Postbox -public final class CachedStickerQueryResult: PostboxCoding { +public final class CachedStickerQueryResult: Codable { public let items: [TelegramMediaFile] public let hash: Int64 public let timestamp: Int32 @@ -11,16 +11,25 @@ public final class CachedStickerQueryResult: PostboxCoding { self.timestamp = timestamp } - public init(decoder: PostboxDecoder) { - self.items = decoder.decodeObjectArrayForKey("it").map { $0 as! TelegramMediaFile } - self.hash = decoder.decodeInt64ForKey("h6", orElse: 0) - self.timestamp = decoder.decodeInt32ForKey("t", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.items = (try container.decode([AdaptedPostboxDecoder.RawObjectData].self, forKey: "it")).map { itemData in + return TelegramMediaFile(decoder: PostboxDecoder(buffer: MemoryBuffer(data: itemData.data))) + } + + self.hash = try container.decode(Int64.self, forKey: "h6") + self.timestamp = try container.decode(Int32.self, forKey: "t") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObjectArray(self.items, forKey: "it") - encoder.encodeInt64(self.hash, forKey: "h6") - encoder.encodeInt32(self.timestamp, forKey: "t") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.items.map { item in + return PostboxEncoder().encodeObjectToRawData(item) + }, forKey: "it") + try container.encode(self.hash, forKey: "h6") + try container.encode(self.timestamp, forKey: "t") } public static func cacheKey(_ query: String) -> ValueBoxKey { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedThemesConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedThemesConfiguration.swift index 2b9f2127d7..c7de0fcc55 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedThemesConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedThemesConfiguration.swift @@ -1,17 +1,21 @@ import Postbox -public final class CachedThemesConfiguration: PostboxCoding { +public final class CachedThemesConfiguration: Codable { public let hash: Int64 public init(hash: Int64) { self.hash = hash } - public init(decoder: PostboxDecoder) { - self.hash = decoder.decodeInt64ForKey("hash6", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.hash = try container.decode(Int64.self, forKey: "hash6") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64(self.hash, forKey: "hash6") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.hash, forKey: "hash6") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedWallpapersConfiguration.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedWallpapersConfiguration.swift index 0d6d2ac9da..d380b2076e 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedWallpapersConfiguration.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_CachedWallpapersConfiguration.swift @@ -1,17 +1,21 @@ import Postbox -public final class CachedWallpapersConfiguration: PostboxCoding { +public final class CachedWallpapersConfiguration: Codable { public let hash: Int64 public init(hash: Int64) { self.hash = hash } - public init(decoder: PostboxDecoder) { - self.hash = decoder.decodeInt64ForKey("hash6", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.hash = try container.decode(Int64.self, forKey: "hash6") } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64(self.hash, forKey: "hash6") + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.hash, forKey: "hash6") } } diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ExportedInvitation.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ExportedInvitation.swift index 152245caa0..1842dbdd4b 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_ExportedInvitation.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_ExportedInvitation.swift @@ -1,6 +1,6 @@ import Postbox -public struct ExportedInvitation: PostboxCoding, Equatable { +public struct ExportedInvitation: Codable, Equatable { public let link: String public let isPermanent: Bool public let isRevoked: Bool @@ -23,44 +23,32 @@ public struct ExportedInvitation: PostboxCoding, Equatable { self.count = count } - public init(decoder: PostboxDecoder) { - self.link = decoder.decodeStringForKey("l", orElse: "") - self.isPermanent = decoder.decodeBoolForKey("permanent", orElse: false) - self.isRevoked = decoder.decodeBoolForKey("revoked", orElse: false) - self.adminId = PeerId(decoder.decodeInt64ForKey("adminId", orElse: 0)) - self.date = decoder.decodeInt32ForKey("date", orElse: 0) - self.startDate = decoder.decodeOptionalInt32ForKey("startDate") - self.expireDate = decoder.decodeOptionalInt32ForKey("expireDate") - self.usageLimit = decoder.decodeOptionalInt32ForKey("usageLimit") - self.count = decoder.decodeOptionalInt32ForKey("count") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.link = try container.decode(String.self, forKey: "l") + self.isPermanent = try container.decode(Bool.self, forKey: "permanent") + self.isRevoked = try container.decode(Bool.self, forKey: "revoked") + self.adminId = PeerId(try container.decode(Int64.self, forKey: "adminId")) + self.date = try container.decode(Int32.self, forKey: "date") + self.startDate = try container.decodeIfPresent(Int32.self, forKey: "startDate") + self.expireDate = try container.decodeIfPresent(Int32.self, forKey: "expireDate") + self.usageLimit = try container.decodeIfPresent(Int32.self, forKey: "usageLimit") + self.count = try container.decodeIfPresent(Int32.self, forKey: "count") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeString(self.link, forKey: "l") - encoder.encodeBool(self.isPermanent, forKey: "permanent") - encoder.encodeBool(self.isRevoked, forKey: "revoked") - encoder.encodeInt64(self.adminId.toInt64(), forKey: "adminId") - encoder.encodeInt32(self.date, forKey: "date") - if let startDate = self.startDate { - encoder.encodeInt32(startDate, forKey: "startDate") - } else { - encoder.encodeNil(forKey: "startDate") - } - if let expireDate = self.expireDate { - encoder.encodeInt32(expireDate, forKey: "expireDate") - } else { - encoder.encodeNil(forKey: "expireDate") - } - if let usageLimit = self.usageLimit { - encoder.encodeInt32(usageLimit, forKey: "usageLimit") - } else { - encoder.encodeNil(forKey: "usageLimit") - } - if let count = self.count { - encoder.encodeInt32(count, forKey: "count") - } else { - encoder.encodeNil(forKey: "count") - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.link, forKey: "l") + try container.encode(self.isPermanent, forKey: "permanent") + try container.encode(self.isRevoked, forKey: "revoked") + try container.encode(self.adminId.toInt64(), forKey: "adminId") + try container.encode(self.date, forKey: "date") + try container.encodeIfPresent(self.startDate, forKey: "startDate") + try container.encodeIfPresent(self.expireDate, forKey: "expireDate") + try container.encodeIfPresent(self.usageLimit, forKey: "usageLimit") + try container.encodeIfPresent(self.count, forKey: "count") } public static func ==(lhs: ExportedInvitation, rhs: ExportedInvitation) -> Bool { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TemporaryTwoStepPasswordToken.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TemporaryTwoStepPasswordToken.swift index 81d327eff3..f64a920627 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TemporaryTwoStepPasswordToken.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TemporaryTwoStepPasswordToken.swift @@ -1,7 +1,7 @@ import Foundation import Postbox -public struct TemporaryTwoStepPasswordToken: PostboxCoding, Equatable { +public struct TemporaryTwoStepPasswordToken: Codable, Equatable { public let token: Data public let validUntilDate: Int32 public let requiresBiometrics: Bool @@ -12,16 +12,20 @@ public struct TemporaryTwoStepPasswordToken: PostboxCoding, Equatable { self.requiresBiometrics = requiresBiometrics } - public init(decoder: PostboxDecoder) { - self.token = decoder.decodeBytesForKey("t")!.makeData() - self.validUntilDate = decoder.decodeInt32ForKey("d", orElse: 0) - self.requiresBiometrics = decoder.decodeInt32ForKey("b", orElse: 0) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.token = try container.decode(Data.self, forKey: "t") + self.validUntilDate = try container.decode(Int32.self, forKey: "d") + self.requiresBiometrics = try container.decode(Int32.self, forKey: "b") != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeBytes(MemoryBuffer(data: self.token), forKey: "t") - encoder.encodeInt32(self.validUntilDate, forKey: "d") - encoder.encodeInt32(self.requiresBiometrics ? 1 : 0, forKey: "b") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.token, forKey: "t") + try container.encode(self.validUntilDate, forKey: "d") + try container.encode((self.requiresBiometrics ? 1 : 0) as Int32, forKey: "b") } public static func ==(lhs: TemporaryTwoStepPasswordToken, rhs: TemporaryTwoStepPasswordToken) -> Bool { diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift index c87dd353b5..01c1c18da7 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Auth/TwoStepVerification.swift @@ -344,7 +344,7 @@ func _internal_cachedTwoStepPasswordToken(postbox: Postbox) -> Signal TemporaryTwoStepPasswordToken? in let key = ValueBoxKey(length: 1) key.setUInt8(0, value: 0) - return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) as? TemporaryTwoStepPasswordToken + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key))?.get(TemporaryTwoStepPasswordToken.self) } } @@ -352,7 +352,7 @@ func _internal_cacheTwoStepPasswordToken(postbox: Postbox, token: TemporaryTwoSt return postbox.transaction { transaction -> Void in let key = ValueBoxKey(length: 1) key.setUInt8(0, value: 0) - if let token = token { + if let token = token.flatMap(CodableEntry.init) { transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key), entry: token, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) } else { transaction.removeItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedTwoStepToken, key: key)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift index e4255094a1..f66890acae 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Calls/GroupCalls.swift @@ -2264,7 +2264,7 @@ func _internal_groupCallDisplayAsAvailablePeers(network: Network, postbox: Postb } } -public final class CachedDisplayAsPeers: PostboxCoding { +public final class CachedDisplayAsPeers: Codable { public let peerIds: [PeerId] public let timestamp: Int32 @@ -2273,14 +2273,18 @@ public final class CachedDisplayAsPeers: PostboxCoding { self.timestamp = timestamp } - public init(decoder: PostboxDecoder) { - self.peerIds = decoder.decodeInt64ArrayForKey("peerIds").map { PeerId($0) } - self.timestamp = decoder.decodeInt32ForKey("timestamp", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.peerIds = (try container.decode([Int64].self, forKey: "peerIds")).map(PeerId.init) + self.timestamp = try container.decode(Int32.self, forKey: "timestamp") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64Array(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") - encoder.encodeInt32(self.timestamp, forKey: "timestamp") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") + try container.encode(self.timestamp, forKey: "timestamp") } } @@ -2297,7 +2301,7 @@ func _internal_cachedGroupCallDisplayAsAvailablePeers(account: Account, peerId: let key = ValueBoxKey(length: 8) key.setInt64(0, value: peerId.toInt64()) return account.postbox.transaction { transaction -> ([FoundPeer], Int32)? in - let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers, key: key)) as? CachedDisplayAsPeers + let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers, key: key))?.get(CachedDisplayAsPeers.self) if let cached = cached { var peers: [FoundPeer] = [] for peerId in cached.peerIds { @@ -2323,7 +2327,9 @@ func _internal_cachedGroupCallDisplayAsAvailablePeers(account: Account, peerId: |> mapToSignal { peers -> Signal<[FoundPeer], NoError> in return account.postbox.transaction { transaction -> [FoundPeer] in let currentTimestamp = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers, key: key), entry: CachedDisplayAsPeers(peerIds: peers.map { $0.peer.id }, timestamp: currentTimestamp), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 10, highWaterItemCount: 20)) + if let entry = CodableEntry(CachedDisplayAsPeers(peerIds: peers.map { $0.peer.id }, timestamp: currentTimestamp)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers, key: key), entry: entry, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 10, highWaterItemCount: 20)) + } return peers } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift index a2533fb7c7..11f8604116 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Localization/Localizations.swift @@ -43,7 +43,7 @@ func _internal_availableLocalizations(postbox: Postbox, network: Network, allowC let cached: Signal<[LocalizationInfo], NoError> if allowCached { cached = postbox.transaction { transaction -> Signal<[LocalizationInfo], NoError> in - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0))) as? CachedLocalizationInfos { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0)))?.get(CachedLocalizationInfos.self) { return .single(entry.list) } return .complete() @@ -56,7 +56,9 @@ func _internal_availableLocalizations(postbox: Postbox, network: Network, allowC |> mapToSignal { languages -> Signal<[LocalizationInfo], NoError> in let infos: [LocalizationInfo] = languages.map(LocalizationInfo.init(apiLanguage:)) return postbox.transaction { transaction -> [LocalizationInfo] in - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0)), entry: CachedLocalizationInfos(list: infos), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + if let entry = CodableEntry(CachedLocalizationInfos(list: infos)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAvailableLocalizations, key: ValueBoxKey(length: 0)), entry: entry, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + } return infos } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift index e6603c5c21..6c87d81cb6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/AdMessages.swift @@ -201,8 +201,8 @@ private class AdMessagesHistoryContextImpl { return postbox.transaction { transaction -> CachedState? in let key = ValueBoxKey(length: 8) key.setInt64(0, value: peerId.toInt64()) - if let entry = transaction.retrieveItemCacheEntryData(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAdMessageStates, key: key)) { - return try? AdaptedPostboxDecoder().decode(CachedState.self, from: entry) + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAdMessageStates, key: key))?.get(CachedState.self) { + return entry } else { return nil } @@ -213,8 +213,8 @@ private class AdMessagesHistoryContextImpl { let key = ValueBoxKey(length: 8) key.setInt64(0, value: peerId.toInt64()) let id = ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedAdMessageStates, key: key) - if let state = state, let stateData = try? AdaptedPostboxEncoder().encode(state) { - transaction.putItemCacheEntryData(id: id, entry: stateData, collectionSpec: collectionSpec) + if let state = state, let entry = CodableEntry(state) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) } else { transaction.removeItemCacheEntry(id: id) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift index 2f95cd54c3..e4290a9a73 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/Polls.swift @@ -151,7 +151,7 @@ func _internal_requestClosePoll(postbox: Postbox, network: Network, stateManager private let cachedPollResultsCollectionSpec = ItemCacheCollectionSpec(lowWaterItemCount: 20, highWaterItemCount: 40) -final class CachedPollOptionResult: PostboxCoding { +final class CachedPollOptionResult: Codable { let peerIds: [PeerId] let count: Int32 @@ -168,14 +168,18 @@ final class CachedPollOptionResult: PostboxCoding { self.count = count } - public init(decoder: PostboxDecoder) { - self.peerIds = decoder.decodeInt64ArrayForKey("peerIds").map(PeerId.init) - self.count = decoder.decodeInt32ForKey("count", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.peerIds = (try container.decode([Int64].self, forKey: "peerIds")).map(PeerId.init) + self.count = try container.decode(Int32.self, forKey: "count") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64Array(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") - encoder.encodeInt32(self.count, forKey: "count") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") + try container.encode(self.count, forKey: "count") } } @@ -206,7 +210,7 @@ private final class PollResultsOptionContext { self.isLoadingMore = true self.disposable.set((account.postbox.transaction { transaction -> (peers: [RenderedPeer], canLoadMore: Bool)? in - let cachedResult = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPollResults, key: CachedPollOptionResult.key(pollId: pollId, optionOpaqueIdentifier: opaqueIdentifier))) as? CachedPollOptionResult + let cachedResult = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPollResults, key: CachedPollOptionResult.key(pollId: pollId, optionOpaqueIdentifier: opaqueIdentifier)))?.get(CachedPollOptionResult.self) if let cachedResult = cachedResult, Int(cachedResult.count) == count { var result: [RenderedPeer] = [] for peerId in cachedResult.peerIds { @@ -294,15 +298,15 @@ private final class PollResultsOptionContext { } } if populateCache { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPollResults, key: CachedPollOptionResult.key(pollId: pollId, optionOpaqueIdentifier: opaqueIdentifier)), entry: CachedPollOptionResult(peerIds: resultPeers.map { $0.peerId }, count: count), collectionSpec: cachedPollResultsCollectionSpec) + if let entry = CodableEntry(CachedPollOptionResult(peerIds: resultPeers.map { $0.peerId }, count: count)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPollResults, key: CachedPollOptionResult.key(pollId: pollId, optionOpaqueIdentifier: opaqueIdentifier)), entry: entry, collectionSpec: cachedPollResultsCollectionSpec) + } } return (resultPeers, Int(count), nextOffset) } } } - #if DEBUG - //return signal |> delay(4.0, queue: .concurrentDefaultQueue()) - #endif + return signal } else { return .single(([], 0, nil)) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift index 14f865ad8f..42394a57d6 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Messages/RequestChatContextResults.swift @@ -9,7 +9,7 @@ public enum RequestChatContextResultsError { case locationRequired } -public final class CachedChatContextResult: PostboxCoding { +public final class CachedChatContextResult: Codable { public let data: Data public let timestamp: Int32 @@ -18,14 +18,18 @@ public final class CachedChatContextResult: PostboxCoding { self.timestamp = timestamp } - public init(decoder: PostboxDecoder) { - self.data = decoder.decodeDataForKey("data") ?? Data() - self.timestamp = decoder.decodeInt32ForKey("timestamp", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.data = try container.decode(Data.self, forKey: "data") + self.timestamp = try container.decode(Int32.self, forKey: "timestamp") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeData(self.data, forKey: "data") - encoder.encodeInt32(self.timestamp, forKey: "timestamp") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.data, forKey: "data") + try container.encode(self.timestamp, forKey: "timestamp") } } @@ -82,7 +86,7 @@ func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId let requestData = RequestData(version: requestVersion, botId: botId, peerId: peerId, query: query) if let keyData = try? JSONEncoder().encode(requestData) { let key = ValueBoxKey(MemoryBuffer(data: keyData)) - if let cachedEntry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedContextResults, key: key)) as? CachedChatContextResult { + if let cachedEntry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedContextResults, key: key))?.get(CachedChatContextResult.self) { if let cachedResult = try? JSONDecoder().decode(ChatContextResultCollection.self, from: cachedEntry.data) { let timestamp = Int32(Date().timeIntervalSince1970) if cachedEntry.timestamp + cachedResult.cacheTimeout > timestamp { @@ -141,7 +145,9 @@ func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId let requestData = RequestData(version: requestVersion, botId: botId, peerId: peerId, query: query) if let keyData = try? JSONEncoder().encode(requestData) { let key = ValueBoxKey(MemoryBuffer(data: keyData)) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedContextResults, key: key), entry: CachedChatContextResult(data: resultData, timestamp: Int32(Date().timeIntervalSince1970)), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedChatContextResult(data: resultData, timestamp: Int32(Date().timeIntervalSince1970))) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedContextResults, key: key), entry: entry, collectionSpec: collectionSpec) + } } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift index 115e641426..7a0915833a 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/InvitationLinks.swift @@ -296,7 +296,7 @@ public struct PeerExportedInvitationsState: Equatable { } } -final class CachedPeerExportedInvitations: PostboxCoding { +final class CachedPeerExportedInvitations: Codable { let invitations: [ExportedInvitation] let canLoadMore: Bool let count: Int32 @@ -314,16 +314,20 @@ final class CachedPeerExportedInvitations: PostboxCoding { self.count = count } - init(decoder: PostboxDecoder) { - self.invitations = decoder.decodeObjectArrayForKey("invitations") - self.canLoadMore = decoder.decodeBoolForKey("canLoadMore", orElse: false) - self.count = decoder.decodeInt32ForKey("count", orElse: 0) + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.invitations = try container.decode([ExportedInvitation].self, forKey: "invitations") + self.canLoadMore = try container.decode(Bool.self, forKey: "canLoadMore") + self.count = try container.decode(Int32.self, forKey: "count") } - func encode(_ encoder: PostboxEncoder) { - encoder.encodeObjectArray(self.invitations, forKey: "invitations") - encoder.encodeBool(self.canLoadMore, forKey: "canLoadMore") - encoder.encodeInt32(self.count, forKey: "count") + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.invitations, forKey: "invitations") + try container.encode(self.canLoadMore, forKey: "canLoadMore") + try container.encode(self.count, forKey: "count") } } @@ -361,7 +365,7 @@ private final class PeerExportedInvitationsContextImpl { if adminId == nil { self.isLoadingMore = true self.disposable.set((account.postbox.transaction { transaction -> CachedPeerExportedInvitations? in - return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked))) as? CachedPeerExportedInvitations + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked)))?.get(CachedPeerExportedInvitations.self) } |> deliverOn(self.queue)).start(next: { [weak self] cachedResult in guard let strongSelf = self else { @@ -448,7 +452,9 @@ private final class PeerExportedInvitationsContextImpl { }) let invitations: [ExportedInvitation] = invites.compactMap { ExportedInvitation(apiExportedInvite: $0) } if populateCache { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked)), entry: CachedPeerExportedInvitations(invitations: invitations, canLoadMore: count >= 50, count: count), collectionSpec: cachedPeerExportedInvitationsCollectionSpec) + if let entry = CodableEntry(CachedPeerExportedInvitations(invitations: invitations, canLoadMore: count >= 50, count: count)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked)), entry: entry, collectionSpec: cachedPeerExportedInvitationsCollectionSpec) + } } return (invitations, count) } @@ -536,7 +542,9 @@ private final class PeerExportedInvitationsContextImpl { let canLoadMore = self.canLoadMore let count = self.count self.updateDisposable.set(self.account.postbox.transaction({ transaction in - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked)), entry: CachedPeerExportedInvitations(invitations: invitations, canLoadMore: canLoadMore, count: count), collectionSpec: cachedPeerExportedInvitationsCollectionSpec) + if let entry = CodableEntry(CachedPeerExportedInvitations(invitations: invitations, canLoadMore: canLoadMore, count: count)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerExportedInvitations, key: CachedPeerExportedInvitations.key(peerId: peerId, revoked: revoked)), entry: entry, collectionSpec: cachedPeerExportedInvitationsCollectionSpec) + } }).start()) } @@ -621,7 +629,7 @@ public struct PeerInvitationImportersState: Equatable { public var count: Int32 } -final class CachedPeerInvitationImporters: PostboxCoding { +final class CachedPeerInvitationImporters: Codable { let peerIds: [PeerId] let dates: [PeerId: Int32] let count: Int32 @@ -647,11 +655,13 @@ final class CachedPeerInvitationImporters: PostboxCoding { self.count = count } - init(decoder: PostboxDecoder) { - self.peerIds = decoder.decodeInt64ArrayForKey("peerIds").map(PeerId.init) + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.peerIds = (try container.decode([Int64].self, forKey: "peerIds")).map(PeerId.init) var dates: [PeerId: Int32] = [:] - let datesArray = decoder.decodeInt64ArrayForKey("dates") + let datesArray = try container.decode([Int64].self, forKey: "dates") for index in stride(from: 0, to: datesArray.endIndex, by: 2) { let userId = datesArray[index] let date = datesArray[index + 1] @@ -660,20 +670,22 @@ final class CachedPeerInvitationImporters: PostboxCoding { } self.dates = dates - self.count = decoder.decodeInt32ForKey("count", orElse: 0) + self.count = try container.decode(Int32.self, forKey: "count") } - func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64Array(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.peerIds.map { $0.toInt64() }, forKey: "peerIds") var dates: [Int64] = [] for (peerId, date) in self.dates { dates.append(peerId.id._internalGetInt64Value()) dates.append(Int64(date)) } - encoder.encodeInt64Array(dates, forKey: "dates") + try container.encode(dates, forKey: "dates") - encoder.encodeInt32(self.count, forKey: "count") + try container.encode(self.count, forKey: "count") } } @@ -704,7 +716,7 @@ private final class PeerInvitationImportersContextImpl { self.isLoadingMore = true self.disposable.set((account.postbox.transaction { transaction -> (peers: [PeerInvitationImportersState.Importer], canLoadMore: Bool)? in - let cachedResult = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerInvitationImporters, key: CachedPeerInvitationImporters.key(peerId: peerId, link: invite.link))) as? CachedPeerInvitationImporters + let cachedResult = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerInvitationImporters, key: CachedPeerInvitationImporters.key(peerId: peerId, link: invite.link)))?.get(CachedPeerInvitationImporters.self) if let cachedResult = cachedResult, Int(cachedResult.count) == count { var result: [PeerInvitationImportersState.Importer] = [] for peerId in cachedResult.peerIds { @@ -796,7 +808,9 @@ private final class PeerInvitationImportersContextImpl { } } if populateCache { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerInvitationImporters, key: CachedPeerInvitationImporters.key(peerId: peerId, link: link)), entry: CachedPeerInvitationImporters(importers: resultImporters, count: count), collectionSpec: cachedPeerInvitationImportersCollectionSpec) + if let entry = CodableEntry(CachedPeerInvitationImporters(importers: resultImporters, count: count)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedPeerInvitationImporters, key: CachedPeerInvitationImporters.key(peerId: peerId, link: link)), entry: entry, collectionSpec: cachedPeerInvitationImportersCollectionSpec) + } } return (resultImporters, count) } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift index 64021a5452..e5ccd9eaf3 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/RecentPeers.swift @@ -19,7 +19,7 @@ func _internal_recentPeers(account: Account) -> Signal { let key = PostboxViewKey.cachedItem(cachedRecentPeersEntryId()) return account.postbox.combinedView(keys: [key]) |> mapToSignal { views -> Signal in - if let value = (views.views[key] as? CachedItemView)?.value as? CachedRecentPeers { + if let value = (views.views[key] as? CachedItemView)?.value?.get(CachedRecentPeers.self) { if value.enabled { return account.postbox.multiplePeersView(value.ids) |> map { view -> RecentPeers in @@ -41,7 +41,7 @@ func _internal_recentPeers(account: Account) -> Signal { } public func _internal_getRecentPeers(transaction: Transaction) -> [PeerId] { - guard let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId()) as? CachedRecentPeers else { + guard let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId())?.get(CachedRecentPeers.self) else { return [] } return entry.ids @@ -51,7 +51,7 @@ func _internal_managedUpdatedRecentPeers(accountPeerId: PeerId, postbox: Postbox let key = PostboxViewKey.cachedItem(cachedRecentPeersEntryId()) let peersEnabled = postbox.combinedView(keys: [key]) |> map { views -> Bool in - if let value = (views.views[key] as? CachedItemView)?.value as? CachedRecentPeers { + if let value = (views.views[key] as? CachedItemView)?.value?.get(CachedRecentPeers.self) { return value.enabled } else { return true @@ -80,12 +80,16 @@ func _internal_managedUpdatedRecentPeers(accountPeerId: PeerId, postbox: Postbox updatePeers(transaction: transaction, peers: peers, update: { return $1 }) updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences) - - transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: CachedRecentPeers(enabled: true, ids: peers.map { $0.id }), collectionSpec: collectionSpec) + + if let entry = CodableEntry(CachedRecentPeers(enabled: true, ids: peers.map { $0.id })) { + transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: entry, collectionSpec: collectionSpec) + } case .topPeersNotModified: break case .topPeersDisabled: - transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: CachedRecentPeers(enabled: false, ids: []), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedRecentPeers(enabled: false, ids: [])) { + transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: entry, collectionSpec: collectionSpec) + } } } } @@ -97,14 +101,16 @@ func _internal_managedUpdatedRecentPeers(accountPeerId: PeerId, postbox: Postbox func _internal_removeRecentPeer(account: Account, peerId: PeerId) -> Signal { return account.postbox.transaction { transaction -> Signal in - guard let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId()) as? CachedRecentPeers else { + guard let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId())?.get(CachedRecentPeers.self) else { return .complete() } if let index = entry.ids.firstIndex(of: peerId) { var updatedIds = entry.ids updatedIds.remove(at: index) - transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: CachedRecentPeers(enabled: entry.enabled, ids: updatedIds), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedRecentPeers(enabled: entry.enabled, ids: updatedIds)) { + transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: entry, collectionSpec: collectionSpec) + } } if let peer = transaction.getPeer(peerId), let apiPeer = apiInputPeer(peer) { return account.network.request(Api.functions.contacts.resetTopPeerRating(category: .topPeerCategoryCorrespondents, peer: apiPeer)) @@ -123,7 +129,7 @@ func _internal_removeRecentPeer(account: Account, peerId: PeerId) -> Signal Signal { return postbox.transaction { transaction -> Signal in var currentValue = true - if let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId()) as? CachedRecentPeers { + if let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId())?.get(CachedRecentPeers.self) { currentValue = entry.enabled } @@ -138,10 +144,14 @@ func _internal_updateRecentPeersEnabled(postbox: Postbox, network: Network, enab |> mapToSignal { _ -> Signal in return postbox.transaction { transaction -> Void in if !enabled { - transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: CachedRecentPeers(enabled: false, ids: []), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedRecentPeers(enabled: false, ids: [])) { + transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: entry, collectionSpec: collectionSpec) + } } else { - let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId()) as? CachedRecentPeers - transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: CachedRecentPeers(enabled: true, ids: entry?.ids ?? []), collectionSpec: collectionSpec) + let entry = transaction.retrieveItemCacheEntry(id: cachedRecentPeersEntryId())?.get(CachedRecentPeers.self) + if let codableEntry = CodableEntry(CachedRecentPeers(enabled: true, ids: entry?.ids ?? [])) { + transaction.putItemCacheEntry(id: cachedRecentPeersEntryId(), entry: codableEntry, collectionSpec: collectionSpec) + } } } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift index 22a4261fd5..c35dd5f68c 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Peers/ResolvePeerByName.swift @@ -24,7 +24,7 @@ func _internal_resolvePeerByName(account: Account, name: String, ageLimit: Int32 } return account.postbox.transaction { transaction -> CachedResolvedByNamePeer? in - return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName))) as? CachedResolvedByNamePeer + return transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName)))?.get(CachedResolvedByNamePeer.self) } |> mapToSignal { cachedEntry -> Signal in let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) if let cachedEntry = cachedEntry, cachedEntry.timestamp <= timestamp && cachedEntry.timestamp >= timestamp - ageLimit { @@ -64,7 +64,9 @@ func _internal_resolvePeerByName(account: Account, name: String, ageLimit: Int32 } let timestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName)), entry: CachedResolvedByNamePeer(peerId: peerId, timestamp: timestamp), collectionSpec: resolvedByNamePeersCollectionSpec) + if let entry = CodableEntry(CachedResolvedByNamePeer(peerId: peerId, timestamp: timestamp)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.resolvedByNamePeers, key: CachedResolvedByNamePeer.key(name: normalizedName)), entry: entry, collectionSpec: resolvedByNamePeersCollectionSpec) + } return peerId } |> castError(Void.self) diff --git a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift index 4ddc2382d5..c101294da2 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/SecureId/SecureIdConfiguration.swift @@ -7,7 +7,7 @@ import TelegramApi public func secureIdConfiguration(postbox: Postbox, network: Network) -> Signal { let cached: Signal = postbox.transaction { transaction -> CachedSecureIdConfiguration? in - if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSecureIdConfiguration, key: ValueBoxKey(length: 0))) as? CachedSecureIdConfiguration { + if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSecureIdConfiguration, key: ValueBoxKey(length: 0)))?.get(CachedSecureIdConfiguration.self) { return entry } else { return nil @@ -35,7 +35,9 @@ public func secureIdConfiguration(postbox: Postbox, network: Network) -> Signal< } } return postbox.transaction { transaction -> SecureIdConfiguration in - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSecureIdConfiguration, key: ValueBoxKey(length: 0)), entry: parsed, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + if let entry = CodableEntry(parsed) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedSecureIdConfiguration, key: ValueBoxKey(length: 0)), entry: entry, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + } return parsed.value } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/CachedStickerPack.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/CachedStickerPack.swift index eac6c812bd..675a037196 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/CachedStickerPack.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/CachedStickerPack.swift @@ -13,8 +13,12 @@ public enum CachedStickerPackResult { } func cacheStickerPack(transaction: Transaction, info: StickerPackCollectionInfo, items: [ItemCollectionItem], reference: StickerPackReference? = nil) { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(info.id)), entry: CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash), collectionSpec: collectionSpec) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: info.shortName.lowercased())), entry: CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(info.id)), entry: entry, collectionSpec: collectionSpec) + } + if let entry = CodableEntry(CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: info.shortName.lowercased())), entry: entry, collectionSpec: collectionSpec) + } if let reference = reference { var namespace: Int32? @@ -33,7 +37,9 @@ func cacheStickerPack(transaction: Transaction, info: StickerPackCollectionInfo, break } if let namespace = namespace, let id = id { - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))), entry: CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedStickerPack(info: info, items: items.map { $0 as! StickerPackItem }, hash: info.hash)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))), entry: entry, collectionSpec: collectionSpec) + } } } } @@ -56,7 +62,7 @@ func _internal_cachedStickerPack(postbox: Postbox, network: Network, reference: var previousHash: Int32? switch reference { case let .id(id, _): - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { previousHash = cached.hash let current: CachedStickerPackResult = .result(info, cached.items, false) if cached.hash != info.hash { @@ -68,7 +74,7 @@ func _internal_cachedStickerPack(postbox: Postbox, network: Network, reference: return (.fetching, true, nil) } case let .name(shortName): - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: shortName.lowercased()))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: shortName.lowercased())))?.get(CachedStickerPack.self), let info = cached.info { previousHash = cached.hash let current: CachedStickerPackResult = .result(info, cached.items, false) if cached.hash != info.hash { @@ -82,7 +88,7 @@ func _internal_cachedStickerPack(postbox: Postbox, network: Network, reference: case .animatedEmoji: let namespace = Namespaces.ItemCollection.CloudAnimatedEmoji let id: ItemCollectionId.Id = 0 - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { previousHash = cached.hash let current: CachedStickerPackResult = .result(info, cached.items, false) if cached.hash != info.hash { @@ -96,7 +102,7 @@ func _internal_cachedStickerPack(postbox: Postbox, network: Network, reference: case let .dice(emoji): let namespace = Namespaces.ItemCollection.CloudDice let id: ItemCollectionId.Id = Int64(murMurHashString32(emoji)) - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { previousHash = cached.hash let current: CachedStickerPackResult = .result(info, cached.items, false) if cached.hash != info.hash { @@ -110,7 +116,7 @@ func _internal_cachedStickerPack(postbox: Postbox, network: Network, reference: case .animatedEmojiAnimations: let namespace = Namespaces.ItemCollection.CloudAnimatedEmojiAnimations let id: ItemCollectionId.Id = 0 - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { previousHash = cached.hash let current: CachedStickerPackResult = .result(info, cached.items, false) if cached.hash != info.hash { @@ -161,7 +167,7 @@ func cachedStickerPack(transaction: Transaction, reference: StickerPackReference return (currentInfo, items, true) } } - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { return (info, cached.items, false) } } @@ -178,7 +184,7 @@ func cachedStickerPack(transaction: Transaction, reference: StickerPackReference } } } - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: shortName.lowercased()))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(shortName: shortName.lowercased())))?.get(CachedStickerPack.self), let info = cached.info { return (info, cached.items, false) } case .animatedEmoji: @@ -190,7 +196,7 @@ func cachedStickerPack(transaction: Transaction, reference: StickerPackReference return (currentInfo, items, true) } } - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { return (info, cached.items, false) } case let .dice(emoji): @@ -202,7 +208,7 @@ func cachedStickerPack(transaction: Transaction, reference: StickerPackReference return (currentInfo, items, true) } } - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { return (info, cached.items, false) } case .animatedEmojiAnimations: @@ -214,7 +220,7 @@ func cachedStickerPack(transaction: Transaction, reference: StickerPackReference return (currentInfo, items, true) } } - if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id)))) as? CachedStickerPack, let info = cached.info { + if let cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerPacks, key: CachedStickerPack.cacheKey(ItemCollectionId(namespace: namespace, id: id))))?.get(CachedStickerPack.self), let info = cached.info { return (info, cached.items, false) } } diff --git a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift index b94dbe42dc..04e39fc56d 100644 --- a/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift +++ b/submodules/TelegramCore/Sources/TelegramEngine/Stickers/SearchStickers.swift @@ -172,7 +172,7 @@ func _internal_searchStickers(account: Account, query: String, scope: SearchStic result.append(contentsOf: installedItems) } - var cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query))) as? CachedStickerQueryResult + var cached = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query)))?.get(CachedStickerQueryResult.self) let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) let appConfiguration: AppConfiguration = transaction.getPreferencesEntry(key: PreferencesKeys.appConfiguration)?.get(AppConfiguration.self) ?? AppConfiguration.defaultValue @@ -240,7 +240,9 @@ func _internal_searchStickers(account: Account, query: String, scope: SearchStic result.append(contentsOf: items) let currentTime = Int32(CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query)), entry: CachedStickerQueryResult(items: files, hash: hash, timestamp: currentTime), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedStickerQueryResult(items: files, hash: hash, timestamp: currentTime)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedStickerQueryResults, key: CachedStickerQueryResult.cacheKey(query)), entry: entry, collectionSpec: collectionSpec) + } return result case .stickersNotModified: diff --git a/submodules/TelegramCore/Sources/Themes.swift b/submodules/TelegramCore/Sources/Themes.swift index b1fa0f1e36..5bed3c4841 100644 --- a/submodules/TelegramCore/Sources/Themes.swift +++ b/submodules/TelegramCore/Sources/Themes.swift @@ -52,7 +52,9 @@ public func telegramThemes(postbox: Postbox, network: Network, accountManager: A entries.append(OrderedItemListEntry(id: id, contents: item)) } transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudThemes, items: entries) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedThemesConfiguration, key: ValueBoxKey(length: 0)), entry: CachedThemesConfiguration(hash: hash), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + if let entry = CodableEntry(CachedThemesConfiguration(hash: hash)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedThemesConfiguration, key: ValueBoxKey(length: 0)), entry: entry, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + } return items } } |> then( @@ -71,7 +73,7 @@ public func telegramThemes(postbox: Postbox, network: Network, accountManager: A return fetch(nil, nil) } else { return postbox.transaction { transaction -> ([TelegramTheme], Int64?) in - let configuration = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedThemesConfiguration, key: ValueBoxKey(length: 0))) as? CachedThemesConfiguration + let configuration = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedThemesConfiguration, key: ValueBoxKey(length: 0)))?.get(CachedThemesConfiguration.self) let items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudThemes) return (items.map { $0.contents as! TelegramTheme }, configuration?.hash) } diff --git a/submodules/TelegramCore/Sources/Wallpapers.swift b/submodules/TelegramCore/Sources/Wallpapers.swift index 5722c84d27..891b43380f 100644 --- a/submodules/TelegramCore/Sources/Wallpapers.swift +++ b/submodules/TelegramCore/Sources/Wallpapers.swift @@ -46,7 +46,9 @@ public func telegramWallpapers(postbox: Postbox, network: Network, forceUpdate: entries.append(OrderedItemListEntry(id: id, contents: item)) } transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers, items: entries) - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedWallpapersConfiguration, key: ValueBoxKey(length: 0)), entry: CachedWallpapersConfiguration(hash: hash), collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + if let entry = CodableEntry(CachedWallpapersConfiguration(hash: hash)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedWallpapersConfiguration, key: ValueBoxKey(length: 0)), entry: entry, collectionSpec: ItemCacheCollectionSpec(lowWaterItemCount: 1, highWaterItemCount: 1)) + } return items } } @@ -56,7 +58,7 @@ public func telegramWallpapers(postbox: Postbox, network: Network, forceUpdate: return fetch(nil, nil) } else { return postbox.transaction { transaction -> ([TelegramWallpaper], Int64?) in - let configuration = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedWallpapersConfiguration, key: ValueBoxKey(length: 0))) as? CachedWallpapersConfiguration + let configuration = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: Namespaces.CachedItemCollection.cachedWallpapersConfiguration, key: ValueBoxKey(length: 0)))?.get(CachedWallpapersConfiguration.self) let items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.CloudWallpapers) if items.count == 0 { return ([.builtin(WallpaperSettings())], 0) diff --git a/submodules/TelegramNotices/Sources/Notices.swift b/submodules/TelegramNotices/Sources/Notices.swift index d45d82d04b..ffe9f04c8c 100644 --- a/submodules/TelegramNotices/Sources/Notices.swift +++ b/submodules/TelegramNotices/Sources/Notices.swift @@ -4,107 +4,78 @@ import TelegramCore import SwiftSignalKit import TelegramPermissions -public final class ApplicationSpecificBoolNotice: NoticeEntry { +public final class ApplicationSpecificBoolNotice: Codable { public init() { } - public init(decoder: PostboxDecoder) { + public init(from decoder: Decoder) throws { } - public func encode(_ encoder: PostboxEncoder) { - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let _ = to as? ApplicationSpecificBoolNotice { - return true - } else { - return false - } + public func encode(to encoder: Encoder) throws { } } -public final class ApplicationSpecificVariantNotice: NoticeEntry { +public final class ApplicationSpecificVariantNotice: Codable { public let value: Bool public init(value: Bool) { self.value = value } - public init(decoder: PostboxDecoder) { - self.value = decoder.decodeInt32ForKey("v", orElse: 0) != 0 + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.value = try container.decode(Int32.self, forKey: "v") != 0 } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.value ? 1 : 0, forKey: "v") - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let to = to as? ApplicationSpecificVariantNotice { - if self.value != to.value { - return false - } - return true - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode((self.value ? 1 : 0) as Int32, forKey: "v") } } -public final class ApplicationSpecificCounterNotice: NoticeEntry { +public final class ApplicationSpecificCounterNotice: Codable { public let value: Int32 public init(value: Int32) { self.value = value } - public init(decoder: PostboxDecoder) { - self.value = decoder.decodeInt32ForKey("v", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.value = try container.decode(Int32.self, forKey: "v") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.value, forKey: "v") - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let to = to as? ApplicationSpecificCounterNotice { - if self.value != to.value { - return false - } - return true - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.value, forKey: "v") } } -public final class ApplicationSpecificTimestampNotice: NoticeEntry { +public final class ApplicationSpecificTimestampNotice: Codable { public let value: Int32 public init(value: Int32) { self.value = value } - public init(decoder: PostboxDecoder) { - self.value = decoder.decodeInt32ForKey("v", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.value = try container.decode(Int32.self, forKey: "v") } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.value, forKey: "v") - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let to = to as? ApplicationSpecificTimestampNotice { - if self.value != to.value { - return false - } - return true - } else { - return false - } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.value, forKey: "v") } } -public final class ApplicationSpecificTimestampAndCounterNotice: NoticeEntry { +public final class ApplicationSpecificTimestampAndCounterNotice: Codable { public let counter: Int32 public let timestamp: Int32 @@ -112,53 +83,39 @@ public final class ApplicationSpecificTimestampAndCounterNotice: NoticeEntry { self.counter = counter self.timestamp = timestamp } - - public init(decoder: PostboxDecoder) { - self.counter = decoder.decodeInt32ForKey("v", orElse: 0) - self.timestamp = decoder.decodeInt32ForKey("t", orElse: 0) + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.counter = try container.decode(Int32.self, forKey: "v") + self.timestamp = try container.decode(Int32.self, forKey: "t") } - - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt32(self.counter, forKey: "v") - encoder.encodeInt32(self.timestamp, forKey: "t") - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let to = to as? ApplicationSpecificTimestampAndCounterNotice { - if self.counter != to.counter || self.timestamp != to.timestamp { - return false - } - return true - } else { - return false - } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.counter, forKey: "v") + try container.encode(self.timestamp, forKey: "t") } } -public final class ApplicationSpecificInt64ArrayNotice: NoticeEntry { +public final class ApplicationSpecificInt64ArrayNotice: Codable { public let values: [Int64] public init(values: [Int64]) { self.values = values } - public init(decoder: PostboxDecoder) { - self.values = decoder.decodeInt64ArrayForKey("v") + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.values = try container.decode([Int64].self, forKey: "v") } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeInt64Array(self.values, forKey: "v") - } - - public func isEqual(to: NoticeEntry) -> Bool { - if let to = to as? ApplicationSpecificInt64ArrayNotice { - if self.values != to.values { - return false - } - return true - } else { - return false - } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.values, forKey: "v") } } @@ -366,13 +323,15 @@ public struct ApplicationSpecificNotice { public static func setIrrelevantPeerGeoReport(postbox: Postbox, peerId: PeerId) -> Signal { return postbox.transaction { transaction -> Void in - transaction.setNoticeEntry(key: ApplicationSpecificNoticeKeys.irrelevantPeerGeoNotice(peerId: peerId), value: ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNoticeEntry(key: ApplicationSpecificNoticeKeys.irrelevantPeerGeoNotice(peerId: peerId), value: entry) + } } } 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 { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.botPaymentLiabilityNotice(peerId: peerId))?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -382,13 +341,15 @@ public struct ApplicationSpecificNotice { public static func setBotPaymentLiability(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.botPaymentLiabilityNotice(peerId: peerId), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.botPaymentLiabilityNotice(peerId: peerId), entry) + } } } 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 { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.botGameNotice(peerId: peerId))?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -398,13 +359,15 @@ public struct ApplicationSpecificNotice { public static func setBotGameNotice(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.botGameNotice(peerId: peerId), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.botGameNotice(peerId: peerId), entry) + } } } 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 { + if let notice = transaction.getNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId))?.get(ApplicationSpecificTimestampNotice.self) { return notice.value } else { return nil @@ -415,7 +378,7 @@ public struct ApplicationSpecificNotice { 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 { + guard let value = view.value?.get(ApplicationSpecificTimestampNotice.self) else { return false } if value.value == 0 { @@ -428,11 +391,13 @@ public struct ApplicationSpecificNotice { 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) { + if let notice = transaction.getNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId))?.get(ApplicationSpecificTimestampNotice.self), (notice.value == 0 || timestamp <= notice.value + 10 * 60) { return false } - - transaction.setNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId), ApplicationSpecificTimestampNotice(value: timestamp)) + + if let entry = CodableEntry(ApplicationSpecificTimestampNotice(value: timestamp)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId), entry) + } return true } @@ -440,13 +405,15 @@ public struct ApplicationSpecificNotice { 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)) + if let entry = CodableEntry(ApplicationSpecificTimestampNotice(value: value)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.inlineBotLocationRequestNotice(peerId: peerId), entry) + } } } public static func getSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage()) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage())?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -456,17 +423,21 @@ public struct ApplicationSpecificNotice { public static func setSecretChatInlineBotUsage(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), entry) + } } } public static func setSecretChatInlineBotUsage(transaction: AccountManagerModifier) { - transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatInlineBotUsage(), entry) + } } public static func getSecretChatLinkPreviews(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool? in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews()) as? ApplicationSpecificVariantNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews())?.get(ApplicationSpecificVariantNotice.self) { return value.value } else { return nil @@ -474,8 +445,8 @@ public struct ApplicationSpecificNotice { } } - public static func getSecretChatLinkPreviews(_ entry: NoticeEntry) -> Bool? { - if let value = entry as? ApplicationSpecificVariantNotice { + public static func getSecretChatLinkPreviews(_ entry: CodableEntry) -> Bool? { + if let value = entry.get(ApplicationSpecificVariantNotice.self) { return value.value } else { return nil @@ -484,12 +455,16 @@ public struct ApplicationSpecificNotice { public static func setSecretChatLinkPreviews(accountManager: AccountManager, value: Bool) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), ApplicationSpecificVariantNotice(value: value)) + if let entry = CodableEntry(ApplicationSpecificVariantNotice(value: value)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), entry) + } } } public static func setSecretChatLinkPreviews(transaction: AccountManagerModifier, value: Bool) { - transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), ApplicationSpecificVariantNotice(value: value)) + if let entry = CodableEntry(ApplicationSpecificVariantNotice(value: value)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.secretChatLinkPreviews(), entry) + } } public static func secretChatLinkPreviewsKey() -> NoticeEntryKey { @@ -498,7 +473,7 @@ public struct ApplicationSpecificNotice { public static func getChatMediaMediaRecordingTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -509,18 +484,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatMediaMediaRecordingTips(), entry) + } } } public static func getArchiveChatTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.archiveChatTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.archiveChatTips())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -531,13 +508,15 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.archiveChatTips())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } let previousValue = currentValue currentValue += Int32(count) - - transaction.setNotice(ApplicationSpecificNoticeKeys.archiveChatTips(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.archiveChatTips(), entry) + } return Int(previousValue) } @@ -546,20 +525,24 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatFolderTips())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } let previousValue = currentValue currentValue += Int32(count) - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatFolderTips(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatFolderTips(), entry) + } return Int(previousValue) } } public static func setArchiveIntroDismissed(transaction: AccountManagerModifier, value: Bool) { - transaction.setNotice(ApplicationSpecificNoticeKeys.archiveIntroDismissed(), ApplicationSpecificVariantNotice(value: value)) + if let entry = CodableEntry(ApplicationSpecificVariantNotice(value: value)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.archiveIntroDismissed(), entry) + } } public static func archiveIntroDismissedKey() -> NoticeEntryKey { @@ -568,7 +551,7 @@ public struct ApplicationSpecificNotice { public static func getProfileCallTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -579,18 +562,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.profileCallTips(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.profileCallTips(), entry) + } } } public static func getSetPublicChannelLink(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.profileCallTips())?.get(ApplicationSpecificCounterNotice.self) { return value.value < 1 } else { return true @@ -600,13 +585,15 @@ public struct ApplicationSpecificNotice { public static func markAsSeenSetPublicChannelLink(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.profileCallTips(), ApplicationSpecificCounterNotice(value: 1)) + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: 1)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.profileCallTips(), entry) + } } } public static func getProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment()) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment())?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -616,13 +603,15 @@ public struct ApplicationSpecificNotice { public static func setProxyAdsAcknowledgment(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.proxyAdsAcknowledgment(), entry) + } } } 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 { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.psaAdsAcknowledgment(peerId: peerId))?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -632,13 +621,15 @@ public struct ApplicationSpecificNotice { public static func setPsaAcknowledgment(accountManager: AccountManager, peerId: PeerId) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.psaAdsAcknowledgment(peerId: peerId), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.psaAdsAcknowledgment(peerId: peerId), entry) + } } } public static func getPasscodeLockTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.passcodeLockTips()) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.passcodeLockTips())?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -648,7 +639,9 @@ public struct ApplicationSpecificNotice { public static func setPasscodeLockTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.passcodeLockTips(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.passcodeLockTips(), entry) + } } } @@ -660,13 +653,15 @@ public struct ApplicationSpecificNotice { guard let noticeKey = permission.noticeKey else { return } - let _ = accountManager.transaction { transaction -> Void in - transaction.setNotice(noticeKey, ApplicationSpecificTimestampNotice(value: value)) - }.start() + let _ = (accountManager.transaction { transaction -> Void in + if let entry = CodableEntry(ApplicationSpecificTimestampNotice(value: value)) { + transaction.setNotice(noticeKey, entry) + } + }).start() } - public static func getTimestampValue(_ entry: NoticeEntry) -> Int32? { - if let value = entry as? ApplicationSpecificTimestampNotice { + public static func getTimestampValue(_ entry: CodableEntry) -> Int32? { + if let value = entry.get(ApplicationSpecificTimestampNotice.self) { return value.value } else { return nil @@ -675,7 +670,7 @@ public struct ApplicationSpecificNotice { public static func getVolumeButtonToUnmute(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip()) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip())?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -685,13 +680,15 @@ public struct ApplicationSpecificNotice { public static func setVolumeButtonToUnmute(accountManager: AccountManager) { let _ = accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.volumeButtonToUnmuteTip(), entry) + } }.start() } public static func getCallsTabTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.callsTabTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.callsTabTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -702,13 +699,15 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.callsTabTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } let previousValue = currentValue currentValue += min(3, Int32(count)) - - transaction.setNotice(ApplicationSpecificNoticeKeys.callsTabTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.callsTabTip(), entry) + } return Int(previousValue) } @@ -716,14 +715,16 @@ public struct ApplicationSpecificNotice { public static func setCallsTabTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.callsTabTip(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.callsTabTip(), entry) + } } } public static func getChatMessageSearchResultsTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -734,18 +735,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageSearchResultsTip(), entry) + } } } public static func getChatMessageOptionsTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -756,18 +759,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip(), entry) + } } } public static func getChatTextSelectionTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -778,18 +783,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatTextSelectionTip(), entry) + } } } public static func getMessageViewsPrivacyTips(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -800,18 +807,20 @@ public struct ApplicationSpecificNotice { public static func incrementMessageViewsPrivacyTips(accountManager: AccountManager, count: Int32 = 1) -> Signal { return accountManager.transaction { transaction -> Void in var currentValue: Int32 = 0 - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - transaction.setNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips(), ApplicationSpecificCounterNotice(value: currentValue)) + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.messageViewsPrivacyTips(), entry) + } } } public static func getThemeChangeTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Bool in - if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.themeChangeTip()) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNotice(ApplicationSpecificNoticeKeys.themeChangeTip())?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false @@ -821,13 +830,15 @@ public struct ApplicationSpecificNotice { public static func markThemeChangeTipAsSeen(accountManager: AccountManager) { let _ = accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.themeChangeTip(), ApplicationSpecificBoolNotice()) + if let entry = CodableEntry(ApplicationSpecificBoolNotice()) { + transaction.setNotice(ApplicationSpecificNoticeKeys.themeChangeTip(), entry) + } }.start() } public static func getLocationProximityAlertTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -838,18 +849,20 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatMessageOptionsTip(), entry) + } } } public static func getNextChatSuggestionTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -860,19 +873,21 @@ public struct ApplicationSpecificNotice { 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 { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } currentValue += count - transaction.setNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip(), ApplicationSpecificCounterNotice(value: currentValue)) + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.nextChatSuggestionTip(), entry) + } } } 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 { + if let value = view.value?.get(ApplicationSpecificInt64ArrayNotice.self) { return value.values } else { return nil @@ -882,13 +897,15 @@ public struct ApplicationSpecificNotice { public static func setDismissedTrendingStickerPacks(accountManager: AccountManager, values: [Int64]) -> Signal { return accountManager.transaction { transaction -> Void in - transaction.setNotice(ApplicationSpecificNoticeKeys.dismissedTrendingStickerPacks(), ApplicationSpecificInt64ArrayNotice(values: values)) + if let entry = CodableEntry(ApplicationSpecificInt64ArrayNotice(values: values)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.dismissedTrendingStickerPacks(), entry) + } } } public static func getChatSpecificThemeLightPreviewTip(accountManager: AccountManager) -> Signal<(Int32, Int32), NoError> { return accountManager.transaction { transaction -> (Int32, Int32) in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip()) as? ApplicationSpecificTimestampAndCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip())?.get(ApplicationSpecificTimestampAndCounterNotice.self) { return (value.counter, value.timestamp) } else { return (0, 0) @@ -899,13 +916,15 @@ public struct ApplicationSpecificNotice { public static func incrementChatSpecificThemeLightPreviewTip(accountManager: AccountManager, count: Int = 1, timestamp: Int32) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip()) as? ApplicationSpecificTimestampAndCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip())?.get(ApplicationSpecificTimestampAndCounterNotice.self) { currentValue = value.counter } let previousValue = currentValue currentValue += Int32(count) - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip(), ApplicationSpecificTimestampAndCounterNotice(counter: currentValue, timestamp: timestamp)) + + if let entry = CodableEntry(ApplicationSpecificTimestampAndCounterNotice(counter: currentValue, timestamp: timestamp)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeLightPreviewTip(), entry) + } return Int(previousValue) } @@ -913,7 +932,7 @@ public struct ApplicationSpecificNotice { public static func getChatSpecificThemeDarkPreviewTip(accountManager: AccountManager) -> Signal<(Int32, Int32), NoError> { return accountManager.transaction { transaction -> (Int32, Int32) in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip()) as? ApplicationSpecificTimestampAndCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip())?.get(ApplicationSpecificTimestampAndCounterNotice.self) { return (value.counter, value.timestamp) } else { return (0, 0) @@ -924,13 +943,15 @@ public struct ApplicationSpecificNotice { public static func incrementChatSpecificThemeDarkPreviewTip(accountManager: AccountManager, count: Int = 1, timestamp: Int32) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip()) as? ApplicationSpecificTimestampAndCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip())?.get(ApplicationSpecificTimestampAndCounterNotice.self) { currentValue = value.counter } let previousValue = currentValue currentValue += Int32(count) - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip(), ApplicationSpecificTimestampAndCounterNotice(counter: currentValue, timestamp: timestamp)) + + if let entry = CodableEntry(ApplicationSpecificTimestampAndCounterNotice(counter: currentValue, timestamp: timestamp)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatSpecificThemeDarkPreviewTip(), entry) + } return Int(previousValue) } @@ -938,7 +959,7 @@ public struct ApplicationSpecificNotice { public static func getChatForwardOptionsTip(accountManager: AccountManager) -> Signal { return accountManager.transaction { transaction -> Int32 in - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { return value.value } else { return 0 @@ -949,13 +970,15 @@ public struct ApplicationSpecificNotice { public static func incrementChatForwardOptionsTip(accountManager: AccountManager, count: Int = 1) -> Signal { return accountManager.transaction { transaction -> Int in var currentValue: Int32 = 0 - if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip()) as? ApplicationSpecificCounterNotice { + if let value = transaction.getNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip())?.get(ApplicationSpecificCounterNotice.self) { currentValue = value.value } let previousValue = currentValue currentValue += Int32(count) - - transaction.setNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip(), ApplicationSpecificCounterNotice(value: currentValue)) + + if let entry = CodableEntry(ApplicationSpecificCounterNotice(value: currentValue)) { + transaction.setNotice(ApplicationSpecificNoticeKeys.chatForwardOptionsTip(), entry) + } return Int(previousValue) } diff --git a/submodules/TelegramUI/Sources/ChatController.swift b/submodules/TelegramUI/Sources/ChatController.swift index afd513db1b..36591ad279 100644 --- a/submodules/TelegramUI/Sources/ChatController.swift +++ b/submodules/TelegramUI/Sources/ChatController.swift @@ -3056,7 +3056,7 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G onlineMemberCount = recentOnlineSignal self.reportIrrelvantGeoNoticePromise.set(context.account.postbox.transaction { transaction -> Bool? in - if let _ = transaction.getNoticeEntry(key: ApplicationSpecificNotice.irrelevantPeerGeoReportKey(peerId: peerId)) as? ApplicationSpecificBoolNotice { + if let _ = transaction.getNoticeEntry(key: ApplicationSpecificNotice.irrelevantPeerGeoReportKey(peerId: peerId))?.get(ApplicationSpecificBoolNotice.self) { return true } else { return false diff --git a/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift b/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift index 3048de66d5..c4ea94c708 100644 --- a/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift +++ b/submodules/TelegramUI/Sources/ChatHistoryEntriesForView.swift @@ -35,7 +35,7 @@ func chatHistoryEntriesForView( if case let .peer(peerId) = location, peerId.namespace == Namespaces.Peer.CloudChannel { for additionalEntry in view.additionalData { if case let .cacheEntry(id, data) = additionalEntry { - if id == cachedChannelAdminRanksEntryId(peerId: peerId), let data = data as? CachedChannelAdminRanks { + if id == cachedChannelAdminRanksEntryId(peerId: peerId), let data = data?.get(CachedChannelAdminRanks.self) { adminRanks = data.ranks } } else if case let .peer(_, peer) = additionalEntry, let channel = peer as? TelegramChannel, !channel.flags.contains(.isGigagroup) { diff --git a/submodules/TelegramUI/Sources/DeclareEncodables.swift b/submodules/TelegramUI/Sources/DeclareEncodables.swift index ab9d486b56..fb6a3a086f 100644 --- a/submodules/TelegramUI/Sources/DeclareEncodables.swift +++ b/submodules/TelegramUI/Sources/DeclareEncodables.swift @@ -14,50 +14,14 @@ import LocationUI import ChatInterfaceState private var telegramUIDeclaredEncodables: Void = { - //declareEncodable(InAppNotificationSettings.self, f: { InAppNotificationSettings(decoder: $0) }) declareEncodable(VideoLibraryMediaResource.self, f: { VideoLibraryMediaResource(decoder: $0) }) declareEncodable(LocalFileVideoMediaResource.self, f: { LocalFileVideoMediaResource(decoder: $0) }) declareEncodable(LocalFileGifMediaResource.self, f: { LocalFileGifMediaResource(decoder: $0) }) declareEncodable(PhotoLibraryMediaResource.self, f: { PhotoLibraryMediaResource(decoder: $0) }) - //declareEncodable(PresentationPasscodeSettings.self, f: { PresentationPasscodeSettings(decoder: $0) }) - //declareEncodable(MediaAutoDownloadSettings.self, f: { MediaAutoDownloadSettings(decoder: $0) }) - //declareEncodable(AutomaticMediaDownloadSettings.self, f: { AutomaticMediaDownloadSettings(decoder: $0) }) - //declareEncodable(GeneratedMediaStoreSettings.self, f: { GeneratedMediaStoreSettings(decoder: $0) }) - //declareEncodable(PresentationThemeSettings.self, f: { PresentationThemeSettings(decoder: $0) }) - declareEncodable(ApplicationSpecificBoolNotice.self, f: { ApplicationSpecificBoolNotice(decoder: $0) }) - declareEncodable(ApplicationSpecificVariantNotice.self, f: { ApplicationSpecificVariantNotice(decoder: $0) }) - declareEncodable(ApplicationSpecificCounterNotice.self, f: { ApplicationSpecificCounterNotice(decoder: $0) }) - declareEncodable(ApplicationSpecificTimestampNotice.self, f: { ApplicationSpecificTimestampNotice(decoder: $0) }) - declareEncodable(ApplicationSpecificTimestampAndCounterNotice.self, f: { ApplicationSpecificTimestampAndCounterNotice(decoder: $0) }) - declareEncodable(ApplicationSpecificInt64ArrayNotice.self, f: { ApplicationSpecificInt64ArrayNotice(decoder: $0) }) - //declareEncodable(CallListSettings.self, f: { CallListSettings(decoder: $0) }) - //declareEncodable(VoiceCallSettings.self, f: { VoiceCallSettings(decoder: $0) }) - //declareEncodable(ExperimentalSettings.self, f: { ExperimentalSettings(decoder: $0) }) - //declareEncodable(ExperimentalUISettings.self, f: { ExperimentalUISettings(decoder: $0) }) - //declareEncodable(MusicPlaybackSettings.self, f: { MusicPlaybackSettings(decoder: $0) }) declareEncodable(ICloudFileResource.self, f: { ICloudFileResource(decoder: $0) }) - //declareEncodable(MediaInputSettings.self, f: { MediaInputSettings(decoder: $0) }) - //declareEncodable(ContactSynchronizationSettings.self, f: { ContactSynchronizationSettings(decoder: $0) }) - declareEncodable(CachedChannelAdminRanks.self, f: { CachedChannelAdminRanks(decoder: $0) }) - //declareEncodable(StickerSettings.self, f: { StickerSettings(decoder: $0) }) - //declareEncodable(InstantPagePresentationSettings.self, f: { InstantPagePresentationSettings(decoder: $0) }) - declareEncodable(InstantPageStoredState.self, f: { InstantPageStoredState(decoder: $0) }) - declareEncodable(InstantPageStoredDetailsState.self, f: { InstantPageStoredDetailsState(decoder: $0) }) - declareEncodable(CachedInstantPage.self, f: { CachedInstantPage(decoder: $0) }) - declareEncodable(CachedWallpaper.self, f: { CachedWallpaper(decoder: $0) }) - //declareEncodable(WatchPresetSettings.self, f: { WatchPresetSettings(decoder: $0) }) - //declareEncodable(WebSearchSettings.self, f: { WebSearchSettings(decoder: $0) }) declareEncodable(RecentWebSearchQueryItem.self, f: { RecentWebSearchQueryItem(decoder: $0) }) declareEncodable(RecentWallpaperSearchQueryItem.self, f: { RecentWallpaperSearchQueryItem(decoder: $0) }) declareEncodable(RecentSettingsSearchQueryItem.self, f: { RecentSettingsSearchQueryItem(decoder: $0) }) - //declareEncodable(VoipDerivedState.self, f: { VoipDerivedState(decoder: $0) }) - //declareEncodable(ChatArchiveSettings.self, f: { ChatArchiveSettings(decoder: $0) }) - declareEncodable(MediaPlaybackStoredState.self, f: { MediaPlaybackStoredState(decoder: $0) }) - //declareEncodable(WebBrowserSettings.self, f: { WebBrowserSettings(decoder: $0) }) - //declareEncodable(IntentsSettings.self, f: { IntentsSettings(decoder: $0) }) - declareEncodable(CachedGeocode.self, f: { CachedGeocode(decoder: $0) }) - //declareEncodable(ChatListFilterSettings.self, f: { ChatListFilterSettings(decoder: $0) }) - //declareEncodable(WidgetSettings.self, f: { WidgetSettings(decoder: $0) }) return }() diff --git a/submodules/TemporaryCachedPeerDataManager/Sources/CachedChannelAdmins.swift b/submodules/TemporaryCachedPeerDataManager/Sources/CachedChannelAdmins.swift index 65f2c6b33b..59f0192f55 100644 --- a/submodules/TemporaryCachedPeerDataManager/Sources/CachedChannelAdmins.swift +++ b/submodules/TemporaryCachedPeerDataManager/Sources/CachedChannelAdmins.swift @@ -3,57 +3,88 @@ import Postbox import TelegramCore import SwiftSignalKit -public enum CachedChannelAdminRank: PostboxCoding, Equatable { +public enum CachedChannelAdminRank: Codable, Equatable { case owner case admin case custom(String) - public init(decoder: PostboxDecoder) { - let value: Int32 = decoder.decodeInt32ForKey("v", orElse: 0) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let value: Int32 = try container.decode(Int32.self, forKey: "v") switch value { case 0: self = .owner case 1: self = .admin case 2: - self = .custom(decoder.decodeStringForKey("s", orElse: "")) + self = .custom(try container.decode(String.self, forKey: "s")) default: self = .admin } } - public func encode(_ encoder: PostboxEncoder) { + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + switch self { case .owner: - encoder.encodeInt32(0, forKey: "v") + try container.encode(0 as Int32, forKey: "v") case .admin: - encoder.encodeInt32(1, forKey: "v") + try container.encode(1 as Int32, forKey: "v") case let .custom(rank): - encoder.encodeInt32(2, forKey: "v") - encoder.encodeString(rank, forKey: "s") + try container.encode(2 as Int32, forKey: "v") + try container.encode(rank, forKey: "s") } } } -public final class CachedChannelAdminRanks: PostboxCoding { - public let ranks: Dictionary +public final class CachedChannelAdminRanks: Codable { + private struct DictionaryKey: Codable, Hashable { + var key: PeerId + + init(_ key: PeerId) { + self.key = key + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + self.key = PeerId(try container.decode(Int64.self, forKey: "k")) + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(self.key.toInt64(), forKey: "k") + } + } - public init(ranks: Dictionary) { + public let ranks: [PeerId: CachedChannelAdminRank] + + public init(ranks: [PeerId: CachedChannelAdminRank]) { self.ranks = ranks } - public init(decoder: PostboxDecoder) { - self.ranks = decoder.decodeObjectDictionaryForKey("ranks", keyDecoder: { decoder in - return PeerId(decoder.decodeInt64ForKey("k", orElse: 0)) - }, valueDecoder: { decoder in - return CachedChannelAdminRank(decoder: decoder) - }) + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let dict = try container.decode([DictionaryKey: CachedChannelAdminRank].self, forKey: "ranks") + var mappedDict: [PeerId: CachedChannelAdminRank] = [:] + for (key, value) in dict { + mappedDict[key.key] = value + } + self.ranks = mappedDict } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObjectDictionary(self.ranks, forKey: "ranks", keyEncoder: { key, encoder in - encoder.encodeInt64(key.toInt64(), forKey: "k") - }) + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + var mappedDict: [DictionaryKey: CachedChannelAdminRank] = [:] + for (k, v) in self.ranks { + mappedDict[DictionaryKey(k)] = v + } + try container.encode(mappedDict, forKey: "ranks") } public static func cacheKey(peerId: PeerId) -> ValueBoxKey { @@ -71,6 +102,8 @@ public func cachedChannelAdminRanksEntryId(peerId: PeerId) -> ItemCacheEntryId { public func updateCachedChannelAdminRanks(postbox: Postbox, peerId: PeerId, ranks: Dictionary) -> Signal { return postbox.transaction { transaction -> Void in - transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: 100, key: CachedChannelAdminRanks.cacheKey(peerId: peerId)), entry: CachedChannelAdminRanks(ranks: ranks), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedChannelAdminRanks(ranks: ranks)) { + transaction.putItemCacheEntry(id: ItemCacheEntryId(collectionId: 100, key: CachedChannelAdminRanks.cacheKey(peerId: peerId)), entry: entry, collectionSpec: collectionSpec) + } } } diff --git a/submodules/WallpaperResources/Sources/WallpaperCache.swift b/submodules/WallpaperResources/Sources/WallpaperCache.swift index 3a0a933cd7..97d4d182b5 100644 --- a/submodules/WallpaperResources/Sources/WallpaperCache.swift +++ b/submodules/WallpaperResources/Sources/WallpaperCache.swift @@ -7,19 +7,24 @@ import TelegramCore import TelegramUIPreferences import PersistentStringHash -public final class CachedWallpaper: PostboxCoding { +public final class CachedWallpaper: Codable { public let wallpaper: TelegramWallpaper public init(wallpaper: TelegramWallpaper) { self.wallpaper = wallpaper } - public init(decoder: PostboxDecoder) { - self.wallpaper = decoder.decodeObjectForKey("wallpaper", decoder: { TelegramWallpaper(decoder: $0) }) as! TelegramWallpaper + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: StringCodingKey.self) + + let wallpaperData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "wallpaper") + self.wallpaper = TelegramWallpaper(decoder: PostboxDecoder(buffer: MemoryBuffer(data: wallpaperData.data))) } - public func encode(_ encoder: PostboxEncoder) { - encoder.encodeObject(self.wallpaper, forKey: "wallpaper") + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: StringCodingKey.self) + + try container.encode(PostboxEncoder().encodeObjectToRawData(self.wallpaper), forKey: "wallpaper") } } @@ -29,7 +34,7 @@ public func cachedWallpaper(account: Account, slug: String, settings: WallpaperS return account.postbox.transaction { transaction -> Signal in let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: slug.persistentHashValue)) - if !update, let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedWallpapers, key: key)) as? CachedWallpaper { + if !update, let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedWallpapers, key: key))?.get(CachedWallpaper.self) { if let settings = settings { return .single(CachedWallpaper(wallpaper: entry.wallpaper.withUpdatedSettings(settings))) } else { @@ -53,8 +58,9 @@ public func cachedWallpaper(account: Account, slug: String, settings: WallpaperS default: break } - let entry = CachedWallpaper(wallpaper: wallpaper) - transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedWallpaper(wallpaper: wallpaper)) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) + } if let settings = settings { return CachedWallpaper(wallpaper: wallpaper.withUpdatedSettings(settings)) } else { @@ -78,6 +84,8 @@ public func updateCachedWallpaper(account: Account, wallpaper: TelegramWallpaper let key = ValueBoxKey(length: 8) key.setInt64(0, value: Int64(bitPattern: file.slug.persistentHashValue)) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.cachedWallpapers, key: key) - transaction.putItemCacheEntry(id: id, entry: CachedWallpaper(wallpaper: wallpaper), collectionSpec: collectionSpec) + if let entry = CodableEntry(CachedWallpaper(wallpaper: wallpaper)) { + transaction.putItemCacheEntry(id: id, entry: entry, collectionSpec: collectionSpec) + } }).start() }