Merge commit '7621e2f8dec938cf48181c8b10afc9b01f444e68' into beta

This commit is contained in:
Ilya Laktyushin
2025-12-06 02:17:48 +04:00
commit 8344b97e03
28070 changed files with 7995182 additions and 0 deletions
@@ -0,0 +1,41 @@
import Foundation
import Postbox
public class DerivedDataMessageAttribute: MessageAttribute {
private struct EntryData: PostboxCoding {
var data: CodableEntry
init(data: CodableEntry) {
self.data = data
}
init(decoder: PostboxDecoder) {
self.data = CodableEntry(data: decoder.decodeDataForKey("d") ?? Data())
}
func encode(_ encoder: PostboxEncoder) {
encoder.encodeData(self.data.data, forKey: "d")
}
}
public let data: [String: CodableEntry]
public init(data: [String: CodableEntry]) {
self.data = data
}
required public init(decoder: PostboxDecoder) {
let data = decoder.decodeObjectDictionaryForKey("d", keyDecoder: { key in
return key.decodeStringForKey("k", orElse: "")
}, valueDecoder: { value in
return EntryData(data: CodableEntry(data: value.decodeDataForKey("d") ?? Data()))
})
self.data = data.mapValues(\.data)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectDictionary(self.data.mapValues(EntryData.init(data:)), forKey: "d", keyEncoder: { k, e in
e.encodeString(k, forKey: "k")
})
}
}
@@ -0,0 +1,27 @@
import Foundation
import Postbox
import TelegramApi
public final class PaidStarsMessageAttribute: Equatable, MessageAttribute {
public let stars: StarsAmount
public let postponeSending: Bool
public init(stars: StarsAmount, postponeSending: Bool) {
self.stars = stars
self.postponeSending = postponeSending
}
required public init(decoder: PostboxDecoder) {
self.stars = decoder.decodeCodable(StarsAmount.self, forKey: "s") ?? StarsAmount(value: 0, nanos: 0)
self.postponeSending = decoder.decodeBoolForKey("ps", orElse: false)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeCodable(self.stars, forKey: "s")
encoder.encodeBool(self.postponeSending, forKey: "ps")
}
public static func ==(lhs: PaidStarsMessageAttribute, rhs: PaidStarsMessageAttribute) -> Bool {
return lhs.stars == rhs.stars && lhs.postponeSending == rhs.postponeSending
}
}
@@ -0,0 +1,23 @@
import Foundation
import Postbox
import TelegramApi
public final class OutgoingQuickReplyMessageAttribute: Equatable, MessageAttribute {
public let shortcut: String
public init(shortcut: String) {
self.shortcut = shortcut
}
required public init(decoder: PostboxDecoder) {
self.shortcut = decoder.decodeStringForKey("s", orElse: "")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.shortcut, forKey: "s")
}
public static func ==(lhs: OutgoingQuickReplyMessageAttribute, rhs: OutgoingQuickReplyMessageAttribute) -> Bool {
return true
}
}
@@ -0,0 +1,23 @@
import Foundation
import Postbox
import TelegramApi
public final class ReportDeliveryMessageAttribute: Equatable, MessageAttribute {
public let untilDate: Int32
public init(untilDate: Int32, isReported: Bool) {
self.untilDate = untilDate
}
required public init(decoder: PostboxDecoder) {
self.untilDate = decoder.decodeInt32ForKey("d", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.untilDate, forKey: "d")
}
public static func ==(lhs: ReportDeliveryMessageAttribute, rhs: ReportDeliveryMessageAttribute) -> Bool {
return lhs.untilDate == rhs.untilDate
}
}
@@ -0,0 +1,23 @@
import Foundation
import Postbox
import TelegramApi
public final class ScheduledRepeatAttribute: Equatable, MessageAttribute {
public let repeatPeriod: Int32
public init(repeatPeriod: Int32) {
self.repeatPeriod = repeatPeriod
}
required public init(decoder: PostboxDecoder) {
self.repeatPeriod = decoder.decodeInt32ForKey("rp", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.repeatPeriod, forKey: "rp")
}
public static func ==(lhs: ScheduledRepeatAttribute, rhs: ScheduledRepeatAttribute) -> Bool {
return lhs.repeatPeriod == rhs.repeatPeriod
}
}
@@ -0,0 +1,123 @@
import Foundation
import Postbox
import TelegramApi
public final class SuggestedPostMessageAttribute: Equatable, MessageAttribute {
public enum State: Int32 {
case accepted = 0
case rejected = 1
}
public let amount: CurrencyAmount?
public let timestamp: Int32?
public let state: State?
public init(amount: CurrencyAmount?, timestamp: Int32?, state: State?) {
self.amount = amount
self.timestamp = timestamp
self.state = state
}
required public init(decoder: PostboxDecoder) {
self.amount = decoder.decodeCodable(CurrencyAmount.self, forKey: "amt")
self.timestamp = decoder.decodeOptionalInt32ForKey("ts")
self.state = decoder.decodeOptionalInt32ForKey("st").flatMap(State.init(rawValue:))
}
public func encode(_ encoder: PostboxEncoder) {
if let amount = self.amount {
encoder.encodeCodable(amount, forKey: "amt")
} else {
encoder.encodeNil(forKey: "amt")
}
if let timestamp = self.timestamp {
encoder.encodeInt32(timestamp, forKey: "ts")
} else {
encoder.encodeNil(forKey: "ts")
}
if let state = self.state {
encoder.encodeInt32(state.rawValue, forKey: "st")
} else {
encoder.encodeNil(forKey: "st")
}
}
public static func ==(lhs: SuggestedPostMessageAttribute, rhs: SuggestedPostMessageAttribute) -> Bool {
if lhs.amount != rhs.amount {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
if lhs.state != rhs.state {
return false
}
return true
}
}
extension SuggestedPostMessageAttribute {
convenience init(apiSuggestedPost: Api.SuggestedPost) {
switch apiSuggestedPost {
case let .suggestedPost(flags, starsAmount, scheduleDate):
var state: State?
if (flags & (1 << 1)) != 0 {
state = .accepted
} else if (flags & (1 << 2)) != 0 {
state = .rejected
}
self.init(amount: starsAmount.flatMap(CurrencyAmount.init(apiAmount:)), timestamp: scheduleDate, state: state)
}
}
func apiSuggestedPost(fixMinTime: Int32?) -> Api.SuggestedPost {
var flags: Int32 = 0
if let state = self.state {
switch state {
case .accepted:
flags |= 1 << 1
case .rejected:
flags |= 1 << 2
}
}
var timestamp = self.timestamp
if let timestampValue = timestamp, let fixMinTime {
if timestampValue < fixMinTime {
timestamp = fixMinTime
}
}
if timestamp != nil {
flags |= 1 << 0
}
var price: Api.StarsAmount?
if let amount = self.amount {
flags |= 1 << 3
price = amount.apiAmount
}
return .suggestedPost(flags: flags, price: price, scheduleDate: timestamp)
}
}
public final class PublishedSuggestedPostMessageAttribute: Equatable, MessageAttribute {
public let currency: CurrencyAmount.Currency
public init(currency: CurrencyAmount.Currency) {
self.currency = currency
}
public init(decoder: PostboxDecoder) {
self.currency = CurrencyAmount.Currency(rawValue: decoder.decodeInt32ForKey("c", orElse: 0)) ?? .stars
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.currency.rawValue, forKey: "c")
}
public static func == (lhs: PublishedSuggestedPostMessageAttribute, rhs: PublishedSuggestedPostMessageAttribute) -> Bool {
if lhs.currency != rhs.currency {
return false
}
return true
}
}
@@ -0,0 +1,112 @@
import Foundation
import Postbox
public struct AccountBackupData: Codable, Equatable {
private enum CodingKeys: String, CodingKey {
case masterDatacenterId
case peerId
case masterDatacenterKey
case masterDatacenterKeyId
case notificationEncryptionKeyId
case notificationEncryptionKey
case additionalDatacenterKeys
}
public struct DatacenterKey: Codable, Equatable {
public var id: Int32
public var keyId: Int64
public var key: Data
public init(
id: Int32,
keyId: Int64,
key: Data
) {
self.id = id
self.keyId = keyId
self.key = key
}
}
public var masterDatacenterId: Int32
public var peerId: Int64
public var masterDatacenterKey: Data
public var masterDatacenterKeyId: Int64
public var notificationEncryptionKeyId: Data?
public var notificationEncryptionKey: Data?
public var additionalDatacenterKeys: [Int32: DatacenterKey]
public init(
masterDatacenterId: Int32,
peerId: Int64,
masterDatacenterKey: Data,
masterDatacenterKeyId: Int64,
notificationEncryptionKeyId: Data?,
notificationEncryptionKey: Data?,
additionalDatacenterKeys: [Int32: DatacenterKey]
) {
self.masterDatacenterId = masterDatacenterId
self.peerId = peerId
self.masterDatacenterKey = masterDatacenterKey
self.masterDatacenterKeyId = masterDatacenterKeyId
self.notificationEncryptionKeyId = notificationEncryptionKeyId
self.notificationEncryptionKey = notificationEncryptionKey
self.additionalDatacenterKeys = additionalDatacenterKeys
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.masterDatacenterId = try container.decode(Int32.self, forKey: .masterDatacenterId)
self.peerId = try container.decode(Int64.self, forKey: .peerId)
self.masterDatacenterKey = try container.decode(Data.self, forKey: .masterDatacenterKey)
self.masterDatacenterKeyId = try container.decode(Int64.self, forKey: .masterDatacenterKeyId)
self.notificationEncryptionKeyId = try container.decodeIfPresent(Data.self, forKey: .notificationEncryptionKeyId)
self.notificationEncryptionKey = try container.decodeIfPresent(Data.self, forKey: .notificationEncryptionKey)
self.additionalDatacenterKeys = try container.decodeIfPresent([Int32: DatacenterKey].self, forKey: .additionalDatacenterKeys) ?? [:]
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.masterDatacenterId, forKey: .masterDatacenterId)
try container.encode(self.peerId, forKey: .peerId)
try container.encode(self.masterDatacenterKey, forKey: .masterDatacenterKey)
try container.encode(self.masterDatacenterKeyId, forKey: .masterDatacenterKeyId)
try container.encodeIfPresent(self.notificationEncryptionKeyId, forKey: .notificationEncryptionKeyId)
try container.encodeIfPresent(self.notificationEncryptionKey, forKey: .notificationEncryptionKey)
try container.encode(self.additionalDatacenterKeys, forKey: .additionalDatacenterKeys)
}
}
public final class AccountBackupDataAttribute: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case data
}
public let data: AccountBackupData?
public init(data: AccountBackupData?) {
self.data = data
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.data = try? JSONDecoder().decode(AccountBackupData.self, from: (try? container.decode(Data.self, forKey: .data)) ?? Data())
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let data = self.data, let serializedData = try? JSONEncoder().encode(data) {
try container.encode(serializedData, forKey: .data)
} else {
try container.encodeNil(forKey: .data)
}
}
public static func ==(lhs: AccountBackupDataAttribute, rhs: AccountBackupDataAttribute) -> Bool {
return lhs.data == rhs.data
}
}
@@ -0,0 +1,40 @@
import Foundation
import Postbox
public enum AccountEnvironment: Int32 {
case production = 0
case test = 1
}
public final class AccountEnvironmentAttribute: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case environment
}
public let environment: AccountEnvironment
public init(environment: AccountEnvironment) {
self.environment = environment
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let environmentValue: Int32 = (try? container.decode(Int32.self, forKey: .environment)) ?? 0
self.environment = AccountEnvironment(rawValue: environmentValue) ?? .production
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.environment.rawValue, forKey: .environment)
}
public static func ==(lhs: AccountEnvironmentAttribute, rhs: AccountEnvironmentAttribute) -> Bool {
if lhs.environment != rhs.environment {
return false
}
return true
}
}
@@ -0,0 +1,33 @@
import Foundation
import Postbox
public final class AccountSortOrderAttribute: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case order
}
public let order: Int32
public init(order: Int32) {
self.order = order
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.order = (try? container.decode(Int32.self, forKey: .order)) ?? 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.order, forKey: .order)
}
public static func ==(lhs: AccountSortOrderAttribute, rhs: AccountSortOrderAttribute) -> Bool {
if lhs.order != rhs.order {
return false
}
return true
}
}
@@ -0,0 +1,27 @@
import Postbox
public struct AppChangelogState: Codable {
public var checkedVersion: String
public var previousVersion: String
public static var `default` = AppChangelogState(checkedVersion: "", previousVersion: "5.0.8")
public init(checkedVersion: String, previousVersion: String) {
self.checkedVersion = checkedVersion
self.previousVersion = previousVersion
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.checkedVersion = (try? container.decode(String.self, forKey: "checkedVersion")) ?? ""
self.previousVersion = (try? container.decode(String.self, forKey: "previousVersion")) ?? ""
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.checkedVersion, forKey: "checkedVersion")
try container.encode(self.previousVersion, forKey: "previousVersion")
}
}
@@ -0,0 +1,30 @@
import Foundation
import Postbox
public struct AppConfiguration: Codable, Equatable {
public var data: JSON?
public var hash: Int32
public static var defaultValue: AppConfiguration {
return AppConfiguration(data: nil, hash: 0)
}
init(data: JSON?, hash: Int32) {
self.data = data
self.hash = hash
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.data = try container.decodeIfPresent(JSON.self, forKey: "data")
self.hash = (try container.decodeIfPresent(Int32.self, forKey: "storedHash")) ?? 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encodeIfPresent(self.data, forKey: "data")
try container.encode(self.hash, forKey: "storedHash")
}
}
@@ -0,0 +1,42 @@
import Foundation
import Postbox
public struct ArchivedStickerPacksInfoId {
public let rawValue: MemoryBuffer
public let id: Int32
init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length == 4)
var idValue: Int32 = 0
memcpy(&idValue, rawValue.memory, 4)
self.id = idValue
}
init(_ id: Int32) {
self.id = id
var idValue: Int32 = id
self.rawValue = MemoryBuffer(memory: malloc(4)!, capacity: 4, length: 4, freeWhenDone: true)
memcpy(self.rawValue.memory, &idValue, 4)
}
}
public final class ArchivedStickerPacksInfo: Codable {
public let count: Int32
init(count: Int32) {
self.count = count
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.count = try container.decode(Int32.self, forKey: "c")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.count, forKey: "c")
}
}
@@ -0,0 +1,77 @@
import Postbox
public class AudioTranscriptionMessageAttribute: MessageAttribute, Equatable {
public enum TranscriptionError: Int32, Error {
case generic = 0
case tooLong = 1
}
public let id: Int64
public let text: String
public let isPending: Bool
public let didRate: Bool
public let error: TranscriptionError?
public var associatedPeerIds: [PeerId] {
return []
}
public init(id: Int64, text: String, isPending: Bool, didRate: Bool, error: TranscriptionError?) {
self.id = id
self.text = text
self.isPending = isPending
self.didRate = didRate
self.error = error
}
required public init(decoder: PostboxDecoder) {
self.id = decoder.decodeInt64ForKey("id", orElse: 0)
self.text = decoder.decodeStringForKey("text", orElse: "")
self.isPending = decoder.decodeBoolForKey("isPending", orElse: false)
self.didRate = decoder.decodeBoolForKey("didRate", orElse: false)
if let errorValue = decoder.decodeOptionalInt32ForKey("error") {
self.error = TranscriptionError(rawValue: errorValue)
} else {
self.error = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.id, forKey: "id")
encoder.encodeString(self.text, forKey: "text")
encoder.encodeBool(self.isPending, forKey: "isPending")
encoder.encodeBool(self.didRate, forKey: "didRate")
if let error = self.error {
encoder.encodeInt32(error.rawValue, forKey: "error")
} else {
encoder.encodeNil(forKey: "error")
}
}
public static func ==(lhs: AudioTranscriptionMessageAttribute, rhs: AudioTranscriptionMessageAttribute) -> Bool {
if lhs.id != rhs.id {
return false
}
if lhs.text != rhs.text {
return false
}
if lhs.isPending != rhs.isPending {
return false
}
if lhs.didRate != rhs.didRate {
return false
}
if lhs.error != rhs.error {
return false
}
return true
}
func merge(withPrevious other: AudioTranscriptionMessageAttribute) -> AudioTranscriptionMessageAttribute {
return AudioTranscriptionMessageAttribute(id: self.id, text: self.text, isPending: self.isPending, didRate: self.didRate || other.didRate, error: self.error)
}
func withDidRate() -> AudioTranscriptionMessageAttribute {
return AudioTranscriptionMessageAttribute(id: self.id, text: self.text, isPending: self.isPending, didRate: true, error: self.error)
}
}
@@ -0,0 +1,26 @@
import Foundation
import Postbox
public class AuthSessionInfoAttribute: MessageAttribute {
public var associatedMessageIds: [MessageId] = []
public let hash: Int64
public let timestamp: Int32
public init(hash: Int64, timestamp: Int32) {
self.hash = hash
self.timestamp = timestamp
}
required public init(decoder: PostboxDecoder) {
self.timestamp = decoder.decodeInt32ForKey("t", orElse: 0)
self.hash = decoder.decodeInt64ForKey("s", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.timestamp, forKey: "t")
encoder.encodeInt64(self.hash, forKey: "s")
}
}
@@ -0,0 +1,20 @@
import Foundation
import Postbox
public class AuthorSignatureMessageAttribute: MessageAttribute {
public let signature: String
public let associatedPeerIds: [PeerId] = []
public init(signature: String) {
self.signature = signature
}
required public init(decoder: PostboxDecoder) {
self.signature = decoder.decodeStringForKey("s", orElse: "")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.signature, forKey: "s")
}
}
@@ -0,0 +1,130 @@
import Postbox
public protocol AccountState: PostboxCoding {
func equalsTo(_ other: AccountState) -> Bool
}
public func ==(lhs: AccountState, rhs: AccountState) -> Bool {
return lhs.equalsTo(rhs)
}
public class AuthorizedAccountState: AccountState {
public final class State: PostboxCoding, Equatable, CustomStringConvertible {
public let pts: Int32
public let qts: Int32
public let date: Int32
public let seq: Int32
public init(pts: Int32, qts: Int32, date: Int32, seq: Int32) {
self.pts = pts
self.qts = qts
self.date = date
self.seq = seq
}
public init(decoder: PostboxDecoder) {
self.pts = decoder.decodeInt32ForKey("pts", orElse: 0)
self.qts = decoder.decodeInt32ForKey("qts", orElse: 0)
self.date = decoder.decodeInt32ForKey("date", orElse: 0)
self.seq = decoder.decodeInt32ForKey("seq", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.pts, forKey: "pts")
encoder.encodeInt32(self.qts, forKey: "qts")
encoder.encodeInt32(self.date, forKey: "date")
encoder.encodeInt32(self.seq, forKey: "seq")
}
public var description: String {
return "(pts: \(pts), qts: \(qts), seq: \(seq), date: \(date))"
}
}
public struct InvalidatedChannel: PostboxCoding, Equatable {
public var peerId: PeerId
public var pts: Int32?
public var validityMarker: Int64
public init(peerId: PeerId, pts: Int32?, validityMarker: Int64) {
self.peerId = peerId
self.pts = pts
self.validityMarker = validityMarker
}
public init(decoder: PostboxDecoder) {
self.peerId = PeerId(decoder.decodeInt64ForKey("i", orElse: 0))
self.pts = decoder.decodeOptionalInt32ForKey("p")
self.validityMarker = decoder.decodeInt64ForKey("m", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.peerId.toInt64(), forKey: "i")
if let pts = self.pts {
encoder.encodeInt32(pts, forKey: "p")
} else {
encoder.encodeNil(forKey: "p")
}
encoder.encodeInt64(self.validityMarker, forKey: "m")
}
}
public let isTestingEnvironment: Bool
public let masterDatacenterId: Int32
public let peerId: PeerId
public let state: State?
public let invalidatedChannels: [InvalidatedChannel]
public required init(decoder: PostboxDecoder) {
self.isTestingEnvironment = decoder.decodeInt32ForKey("isTestingEnvironment", orElse: 0) != 0
self.masterDatacenterId = decoder.decodeInt32ForKey("masterDatacenterId", orElse: 0)
self.peerId = PeerId(decoder.decodeInt64ForKey("peerId", orElse: 0))
self.state = decoder.decodeObjectForKey("state", decoder: { return State(decoder: $0) }) as? State
self.invalidatedChannels = decoder.decodeObjectArrayWithDecoderForKey("invalidatedChannels")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.isTestingEnvironment ? 1 : 0, forKey: "isTestingEnvironment")
encoder.encodeInt32(self.masterDatacenterId, forKey: "masterDatacenterId")
encoder.encodeInt64(self.peerId.toInt64(), forKey: "peerId")
if let state = self.state {
encoder.encodeObject(state, forKey: "state")
}
encoder.encodeObjectArray(self.invalidatedChannels, forKey: "invalidatedChannels")
}
public init(isTestingEnvironment: Bool, masterDatacenterId: Int32, peerId: PeerId, state: State?, invalidatedChannels: [InvalidatedChannel]) {
self.isTestingEnvironment = isTestingEnvironment
self.masterDatacenterId = masterDatacenterId
self.peerId = peerId
self.state = state
self.invalidatedChannels = invalidatedChannels
}
public func changedState(_ state: State) -> AuthorizedAccountState {
return AuthorizedAccountState(isTestingEnvironment: self.isTestingEnvironment, masterDatacenterId: self.masterDatacenterId, peerId: self.peerId, state: state, invalidatedChannels: self.invalidatedChannels)
}
public func withInvalidatedChannels(_ invalidatedChannels: [InvalidatedChannel]) -> AuthorizedAccountState {
return AuthorizedAccountState(isTestingEnvironment: self.isTestingEnvironment, masterDatacenterId: self.masterDatacenterId, peerId: self.peerId, state: self.state, invalidatedChannels: invalidatedChannels)
}
public func equalsTo(_ other: AccountState) -> Bool {
if let other = other as? AuthorizedAccountState {
return self.isTestingEnvironment == other.isTestingEnvironment && self.masterDatacenterId == other.masterDatacenterId &&
self.peerId == other.peerId &&
self.state == other.state &&
self.invalidatedChannels == other.invalidatedChannels
} else {
return false
}
}
}
public func ==(lhs: AuthorizedAccountState.State, rhs: AuthorizedAccountState.State) -> Bool {
return lhs.pts == rhs.pts &&
lhs.qts == rhs.qts &&
lhs.date == rhs.date &&
lhs.seq == rhs.seq
}
@@ -0,0 +1,99 @@
import Postbox
public enum AutodownloadPreset {
case low
case medium
case high
}
public struct AutodownloadPresetSettings: Codable {
public let disabled: Bool
public let photoSizeMax: Int64
public let videoSizeMax: Int64
public let fileSizeMax: Int64
public let preloadLargeVideo: Bool
public let lessDataForPhoneCalls: Bool
public let videoUploadMaxbitrate: Int32
public init(disabled: Bool, photoSizeMax: Int64, videoSizeMax: Int64, fileSizeMax: Int64, preloadLargeVideo: Bool, lessDataForPhoneCalls: Bool, videoUploadMaxbitrate: Int32) {
self.disabled = disabled
self.photoSizeMax = photoSizeMax
self.videoSizeMax = videoSizeMax
self.fileSizeMax = fileSizeMax
self.preloadLargeVideo = preloadLargeVideo
self.lessDataForPhoneCalls = lessDataForPhoneCalls
self.videoUploadMaxbitrate = videoUploadMaxbitrate
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.disabled = ((try? container.decode(Int32.self, forKey: "disabled")) ?? 0) != 0
if let photoSizeMax = try? container.decode(Int64.self, forKey: "photoSizeMax64") {
self.photoSizeMax = photoSizeMax
} else {
self.photoSizeMax = Int64((try? container.decode(Int32.self, forKey: "photoSizeMax")) ?? 0)
}
if let videoSizeMax = try? container.decode(Int64.self, forKey: "videoSizeMax64") {
self.videoSizeMax = videoSizeMax
} else {
self.videoSizeMax = Int64((try? container.decode(Int32.self, forKey: "videoSizeMax")) ?? 0)
}
if let fileSizeMax = try? container.decode(Int64.self, forKey: "fileSizeMax64") {
self.fileSizeMax = fileSizeMax
} else {
self.fileSizeMax = Int64((try? container.decode(Int32.self, forKey: "fileSizeMax")) ?? 0)
}
self.preloadLargeVideo = ((try? container.decode(Int32.self, forKey: "preloadLargeVideo")) ?? 0) != 0
self.lessDataForPhoneCalls = ((try? container.decode(Int32.self, forKey: "lessDataForPhoneCalls")) ?? 0) != 0
self.videoUploadMaxbitrate = (try? container.decode(Int32.self, forKey: "videoUploadMaxbitrate")) ?? 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode((self.disabled ? 1 : 0) as Int32, forKey: "disabled")
try container.encode(self.photoSizeMax, forKey: "photoSizeMax64")
try container.encode(self.videoSizeMax, forKey: "videoSizeMax64")
try container.encode(self.fileSizeMax, forKey: "fileSizeMax64")
try container.encode((self.preloadLargeVideo ? 1 : 0) as Int32, forKey: "preloadLargeVideo")
try container.encode((self.lessDataForPhoneCalls ? 1 : 0) as Int32, forKey: "lessDataForPhoneCalls")
try container.encode(self.videoUploadMaxbitrate, forKey: "videoUploadMaxbitrate")
}
}
public struct AutodownloadSettings: Codable {
public let lowPreset: AutodownloadPresetSettings
public let mediumPreset: AutodownloadPresetSettings
public let highPreset: AutodownloadPresetSettings
public static var defaultSettings: AutodownloadSettings {
return AutodownloadSettings(
lowPreset: AutodownloadPresetSettings(disabled: false, photoSizeMax: 1 * 1024 * 1024, videoSizeMax: 0, fileSizeMax: 0, preloadLargeVideo: false, lessDataForPhoneCalls: true, videoUploadMaxbitrate: 0),
mediumPreset: AutodownloadPresetSettings(disabled: false, photoSizeMax: 1 * 1024 * 1024, videoSizeMax: Int64(2.5 * 1024 * 1024), fileSizeMax: 1 * 1024 * 1024, preloadLargeVideo: false, lessDataForPhoneCalls: false, videoUploadMaxbitrate: 0),
highPreset: AutodownloadPresetSettings(disabled: false, photoSizeMax: 1 * 1024 * 1024, videoSizeMax: 10 * 1024 * 1024, fileSizeMax: 3 * 1024 * 1024, preloadLargeVideo: false, lessDataForPhoneCalls: false, videoUploadMaxbitrate: 0))
}
public init(lowPreset: AutodownloadPresetSettings, mediumPreset: AutodownloadPresetSettings, highPreset: AutodownloadPresetSettings) {
self.lowPreset = lowPreset
self.mediumPreset = mediumPreset
self.highPreset = highPreset
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.lowPreset = (try? container.decode(AutodownloadPresetSettings.self, forKey: "lowPreset")) ?? AutodownloadSettings.defaultSettings.lowPreset
self.mediumPreset = (try? container.decode(AutodownloadPresetSettings.self, forKey: "mediumPreset")) ?? AutodownloadSettings.defaultSettings.mediumPreset
self.highPreset = (try? container.decode(AutodownloadPresetSettings.self, forKey: "highPreset")) ?? AutodownloadSettings.defaultSettings.highPreset
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.lowPreset, forKey: "lowPreset")
try container.encode(self.mediumPreset, forKey: "mediumPreset")
try container.encode(self.highPreset, forKey: "highPreset")
}
}
@@ -0,0 +1,167 @@
import Foundation
import Postbox
public let viewOnceTimeout: Int32 = 0x7fffffff
public class AutoremoveTimeoutMessageAttribute: MessageAttribute {
public let timeout: Int32
public let countdownBeginTime: Int32?
public var associatedMessageIds: [MessageId] = []
public let automaticTimestampBasedAttribute: (UInt16, Int32)?
public init(timeout: Int32, countdownBeginTime: Int32?) {
self.timeout = timeout
self.countdownBeginTime = countdownBeginTime
if let countdownBeginTime = countdownBeginTime {
self.automaticTimestampBasedAttribute = (0, countdownBeginTime + timeout)
} else {
self.automaticTimestampBasedAttribute = nil
}
}
required public init(decoder: PostboxDecoder) {
self.timeout = decoder.decodeInt32ForKey("t", orElse: 0)
self.countdownBeginTime = decoder.decodeOptionalInt32ForKey("c")
if let countdownBeginTime = self.countdownBeginTime {
self.automaticTimestampBasedAttribute = (0, countdownBeginTime + self.timeout)
} else {
self.automaticTimestampBasedAttribute = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.timeout, forKey: "t")
if let countdownBeginTime = self.countdownBeginTime {
encoder.encodeInt32(countdownBeginTime, forKey: "c")
} else {
encoder.encodeNil(forKey: "c")
}
}
}
public class AutoclearTimeoutMessageAttribute: MessageAttribute {
public let timeout: Int32
public let countdownBeginTime: Int32?
public var associatedMessageIds: [MessageId] = []
public let automaticTimestampBasedAttribute: (UInt16, Int32)?
public init(timeout: Int32, countdownBeginTime: Int32?) {
self.timeout = timeout
self.countdownBeginTime = countdownBeginTime
if let countdownBeginTime = countdownBeginTime {
if self.timeout == viewOnceTimeout {
self.automaticTimestampBasedAttribute = (1, countdownBeginTime)
} else {
self.automaticTimestampBasedAttribute = (1, countdownBeginTime + timeout)
}
} else {
self.automaticTimestampBasedAttribute = nil
}
}
required public init(decoder: PostboxDecoder) {
self.timeout = decoder.decodeInt32ForKey("t", orElse: 0)
self.countdownBeginTime = decoder.decodeOptionalInt32ForKey("c")
if let countdownBeginTime = self.countdownBeginTime {
if self.timeout == viewOnceTimeout {
self.automaticTimestampBasedAttribute = (1, countdownBeginTime)
} else {
self.automaticTimestampBasedAttribute = (1, countdownBeginTime + self.timeout)
}
} else {
self.automaticTimestampBasedAttribute = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.timeout, forKey: "t")
if let countdownBeginTime = self.countdownBeginTime {
encoder.encodeInt32(countdownBeginTime, forKey: "c")
} else {
encoder.encodeNil(forKey: "c")
}
}
}
public extension Message {
var autoremoveAttribute: AutoremoveTimeoutMessageAttribute? {
for attribute in self.attributes {
if let attribute = attribute as? AutoremoveTimeoutMessageAttribute {
return attribute
}
}
return nil
}
var autoclearAttribute: AutoclearTimeoutMessageAttribute? {
for attribute in self.attributes {
if let attribute = attribute as? AutoclearTimeoutMessageAttribute {
return attribute
}
}
return nil
}
var minAutoremoveOrClearTimeout: Int32? {
var timeout: Int32?
for attribute in self.attributes {
if let attribute = attribute as? AutoremoveTimeoutMessageAttribute {
if attribute.timeout == viewOnceTimeout {
return attribute.timeout
}
if let timeoutValue = timeout {
timeout = min(timeoutValue, attribute.timeout)
} else {
timeout = attribute.timeout
}
} else if let attribute = attribute as? AutoclearTimeoutMessageAttribute {
if attribute.timeout == viewOnceTimeout {
return attribute.timeout
}
if let timeoutValue = timeout {
timeout = min(timeoutValue, attribute.timeout)
} else {
timeout = attribute.timeout
}
}
}
return timeout
}
var containsSecretMedia: Bool {
guard let timeout = self.minAutoremoveOrClearTimeout else {
return false
}
if timeout > 1 * 60 && timeout != viewOnceTimeout {
return false
}
for media in self.media {
switch media {
case _ as TelegramMediaImage:
return true
case let file as TelegramMediaFile:
if file.isVideo || file.isAnimated || file.isVoice || file.isMusic {
return true
}
default:
break
}
}
return false
}
var isSelfExpiring: Bool {
return self.minAutoremoveOrClearTimeout != nil
}
}
@@ -0,0 +1,20 @@
import Foundation
import Postbox
public class BoostCountMessageAttribute: MessageAttribute {
public let count: Int
public var associatedMessageIds: [MessageId] = []
public init(count: Int) {
self.count = count
}
required public init(decoder: PostboxDecoder) {
self.count = Int(decoder.decodeInt32ForKey("c", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(Int32(self.count), forKey: "c")
}
}
@@ -0,0 +1,215 @@
import Foundation
import Postbox
public struct BotCommand: PostboxCoding, Hashable {
public let text: String
public let description: String
public init(text: String, description: String) {
self.text = text
self.description = description
}
public init(decoder: PostboxDecoder) {
self.text = decoder.decodeStringForKey("t", orElse: "")
self.description = decoder.decodeStringForKey("d", orElse: "")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.text, forKey: "t")
encoder.encodeString(self.description, forKey: "d")
}
}
public enum BotMenuButton: PostboxCoding, Hashable {
case commands
case webView(text: String, url: String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("v", orElse: 0) {
case 1:
self = .webView(text: decoder.decodeStringForKey("t", orElse: ""), url: decoder.decodeStringForKey("u", orElse: ""))
default:
self = .commands
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .commands:
encoder.encodeInt32(0, forKey: "v")
case let .webView(text, url):
encoder.encodeInt32(1, forKey: "v")
encoder.encodeString(text, forKey: "t")
encoder.encodeString(url, forKey: "u")
}
}
}
public struct BotAppSettings: PostboxCoding, Equatable {
public let placeholderData: Data?
public let backgroundColor: Int32?
public let backgroundDarkColor: Int32?
public let headerColor: Int32?
public let headerDarkColor: Int32?
public init(placeholderData: Data?, backgroundColor: Int32?, backgroundDarkColor: Int32?, headerColor: Int32?, headerDarkColor: Int32?) {
self.placeholderData = placeholderData
self.backgroundColor = backgroundColor
self.backgroundDarkColor = backgroundDarkColor
self.headerColor = headerColor
self.headerDarkColor = headerDarkColor
}
public init(decoder: PostboxDecoder) {
self.placeholderData = decoder.decodeDataForKey("pd")
self.backgroundColor = decoder.decodeOptionalInt32ForKey("b")
self.backgroundDarkColor = decoder.decodeOptionalInt32ForKey("bd")
self.headerColor = decoder.decodeOptionalInt32ForKey("h")
self.headerDarkColor = decoder.decodeOptionalInt32ForKey("hd")
}
public func encode(_ encoder: PostboxEncoder) {
if let placeholderData = self.placeholderData {
encoder.encodeData(placeholderData, forKey: "pd")
} else {
encoder.encodeNil(forKey: "pd")
}
if let backgroundColor = self.backgroundColor {
encoder.encodeInt32(backgroundColor, forKey: "b")
} else {
encoder.encodeNil(forKey: "b")
}
if let backgroundDarkColor = self.backgroundDarkColor {
encoder.encodeInt32(backgroundDarkColor, forKey: "bd")
} else {
encoder.encodeNil(forKey: "bd")
}
if let headerColor = self.headerColor {
encoder.encodeInt32(headerColor, forKey: "h")
} else {
encoder.encodeNil(forKey: "h")
}
if let headerDarkColor = self.headerDarkColor {
encoder.encodeInt32(headerDarkColor, forKey: "hd")
} else {
encoder.encodeNil(forKey: "hd")
}
}
}
public struct BotVerifierSettings: PostboxCoding, Equatable {
public let iconFileId: Int64
public let companyName: String
public let customDescription: String?
public let canModifyDescription: Bool
public init(iconFileId: Int64, companyName: String, customDescription: String?, canModifyDescription: Bool) {
self.iconFileId = iconFileId
self.companyName = companyName
self.customDescription = customDescription
self.canModifyDescription = canModifyDescription
}
public init(decoder: PostboxDecoder) {
self.iconFileId = decoder.decodeInt64ForKey("i", orElse: 0)
self.companyName = decoder.decodeStringForKey("cn", orElse: "")
self.customDescription = decoder.decodeOptionalStringForKey("d")
self.canModifyDescription = decoder.decodeBoolForKey("md", orElse: false)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.iconFileId, forKey: "i")
encoder.encodeString(self.companyName, forKey: "cn")
if let customDescription = self.customDescription {
encoder.encodeString(customDescription, forKey: "d")
} else {
encoder.encodeNil(forKey: "d")
}
encoder.encodeBool(self.canModifyDescription, forKey: "md")
}
}
public final class BotInfo: PostboxCoding, Equatable {
public let description: String
public let photo: TelegramMediaImage?
public let video: TelegramMediaFile?
public let commands: [BotCommand]
public let menuButton: BotMenuButton
public let privacyPolicyUrl: String?
public let appSettings: BotAppSettings?
public let verifierSettings: BotVerifierSettings?
public init(description: String, photo: TelegramMediaImage?, video: TelegramMediaFile?, commands: [BotCommand], menuButton: BotMenuButton, privacyPolicyUrl: String?, appSettings: BotAppSettings?, verifierSettings: BotVerifierSettings?) {
self.description = description
self.photo = photo
self.video = video
self.commands = commands
self.menuButton = menuButton
self.privacyPolicyUrl = privacyPolicyUrl
self.appSettings = appSettings
self.verifierSettings = verifierSettings
}
public init(decoder: PostboxDecoder) {
self.description = decoder.decodeStringForKey("d", orElse: "")
if let photo = decoder.decodeObjectForKey("ph", decoder: { TelegramMediaImage(decoder: $0) }) as? TelegramMediaImage {
self.photo = photo
} else {
self.photo = nil
}
if let video = decoder.decodeObjectForKey("vid", decoder: { TelegramMediaFile(decoder: $0) }) as? TelegramMediaFile {
self.video = video
} else {
self.video = nil
}
self.commands = decoder.decodeObjectArrayWithDecoderForKey("c")
self.menuButton = (decoder.decodeObjectForKey("b", decoder: { BotMenuButton(decoder: $0) }) as? BotMenuButton) ?? .commands
self.privacyPolicyUrl = decoder.decodeOptionalStringForKey("pp")
if let appSettings = decoder.decodeObjectForKey("as", decoder: { BotAppSettings(decoder: $0) }) as? BotAppSettings {
self.appSettings = appSettings
} else {
self.appSettings = nil
}
if let verifierSettings = decoder.decodeObjectForKey("vs", decoder: { BotVerifierSettings(decoder: $0) }) as? BotVerifierSettings {
self.verifierSettings = verifierSettings
} else {
self.verifierSettings = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.description, forKey: "d")
if let photo = self.photo {
encoder.encodeObject(photo, forKey: "ph")
} else {
encoder.encodeNil(forKey: "ph")
}
if let video = self.video {
encoder.encodeObject(video, forKey: "vid")
} else {
encoder.encodeNil(forKey: "vid")
}
encoder.encodeObjectArray(self.commands, forKey: "c")
encoder.encodeObject(self.menuButton, forKey: "b")
if let privacyPolicyUrl = self.privacyPolicyUrl {
encoder.encodeString(privacyPolicyUrl, forKey: "pp")
} else {
encoder.encodeNil(forKey: "pp")
}
if let appSettings = self.appSettings {
encoder.encodeObject(appSettings, forKey: "as")
} else {
encoder.encodeNil(forKey: "as")
}
if let verifierSettings = self.verifierSettings {
encoder.encodeObject(verifierSettings, forKey: "vs")
} else {
encoder.encodeNil(forKey: "vs")
}
}
public static func ==(lhs: BotInfo, rhs: BotInfo) -> Bool {
return lhs.description == rhs.description && lhs.commands == rhs.commands && lhs.menuButton == rhs.menuButton && lhs.photo == rhs.photo && lhs.privacyPolicyUrl == rhs.privacyPolicyUrl && lhs.appSettings == rhs.appSettings && lhs.verifierSettings == rhs.verifierSettings
}
}
@@ -0,0 +1,152 @@
import Foundation
import Postbox
public struct CacheStorageSettings: Codable, Equatable {
public enum PeerStorageCategory: String, Codable, Hashable, CaseIterable {
case privateChats = "privateChats"
case groups = "groups"
case channels = "channels"
case stories = "stories"
}
private struct CategoryStorageTimeoutRepresentation: Codable {
var key: PeerStorageCategory
var value: Int32
}
public var defaultCacheStorageTimeout: Int32
public var defaultCacheStorageLimitGigabytes: Int32
public var categoryStorageTimeout: [PeerStorageCategory: Int32]
public static var defaultSettings: CacheStorageSettings {
return CacheStorageSettings(
defaultCacheStorageTimeout: Int32.max,
defaultCacheStorageLimitGigabytes: Int32.max,
categoryStorageTimeout: [
.privateChats: Int32.max,
.groups: Int32(31 * 24 * 60 * 60),
.channels: Int32(7 * 24 * 60 * 60),
.stories: Int32(2 * 24 * 60 * 60)
]
)
}
public init(
defaultCacheStorageTimeout: Int32,
defaultCacheStorageLimitGigabytes: Int32,
categoryStorageTimeout: [PeerStorageCategory: Int32]
) {
self.defaultCacheStorageTimeout = defaultCacheStorageTimeout
self.defaultCacheStorageLimitGigabytes = defaultCacheStorageLimitGigabytes
self.categoryStorageTimeout = categoryStorageTimeout
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.defaultCacheStorageTimeout = (try? container.decode(Int32.self, forKey: "dt")) ?? Int32.max
if let legacyValue = try container.decodeIfPresent(Int32.self, forKey: "dl") {
self.defaultCacheStorageLimitGigabytes = legacyValue
} else if let value = try container.decodeIfPresent(Int32.self, forKey: "sizeLimit") {
self.defaultCacheStorageLimitGigabytes = value
} else {
self.defaultCacheStorageLimitGigabytes = Int32.max
}
if let data = try container.decodeIfPresent(Data.self, forKey: "categoryStorageTimeoutJson") {
if let items = try? JSONDecoder().decode([CategoryStorageTimeoutRepresentation].self, from: data) {
var categoryStorageTimeout: [PeerStorageCategory: Int32] = [:]
for item in items {
categoryStorageTimeout[item.key] = item.value
}
for key in PeerStorageCategory.allCases {
if categoryStorageTimeout[key] == nil, let value = CacheStorageSettings.defaultSettings.categoryStorageTimeout[key] {
categoryStorageTimeout[key] = value
}
}
self.categoryStorageTimeout = categoryStorageTimeout
} else {
self.categoryStorageTimeout = CacheStorageSettings.defaultSettings.categoryStorageTimeout
}
} else {
self.categoryStorageTimeout = CacheStorageSettings.defaultSettings.categoryStorageTimeout
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.defaultCacheStorageTimeout, forKey: "dt")
try container.encode(self.defaultCacheStorageLimitGigabytes, forKey: "dl")
var categoryStorageTimeoutValues: [CategoryStorageTimeoutRepresentation] = []
for (key, value) in self.categoryStorageTimeout {
categoryStorageTimeoutValues.append(CategoryStorageTimeoutRepresentation(key: key, value: value))
}
if let data = try? JSONEncoder().encode(categoryStorageTimeoutValues) {
try container.encode(data, forKey: "categoryStorageTimeoutJson")
}
}
}
public struct AccountSpecificCacheStorageSettings: Codable, Equatable {
private struct PeerStorageTimeoutExceptionRepresentation: Codable {
var key: PeerId
var value: Int32
}
public struct Value : Equatable {
public let key: PeerId
public let value: Int32
public init(key: PeerId, value: Int32) {
self.key = key
self.value = value
}
}
public var peerStorageTimeoutExceptions: [Value]
public static var defaultSettings: AccountSpecificCacheStorageSettings {
return AccountSpecificCacheStorageSettings(
peerStorageTimeoutExceptions: []
)
}
public init(
peerStorageTimeoutExceptions: [Value]
) {
self.peerStorageTimeoutExceptions = peerStorageTimeoutExceptions
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let data = try container.decodeIfPresent(Data.self, forKey: "peerStorageTimeoutExceptionsJson") {
if let items = try? JSONDecoder().decode([PeerStorageTimeoutExceptionRepresentation].self, from: data) {
var peerStorageTimeoutExceptions: [Value] = []
for item in items {
peerStorageTimeoutExceptions.append(.init(key: item.key, value: item.value))
}
self.peerStorageTimeoutExceptions = peerStorageTimeoutExceptions
} else {
self.peerStorageTimeoutExceptions = AccountSpecificCacheStorageSettings.defaultSettings.peerStorageTimeoutExceptions
}
} else {
self.peerStorageTimeoutExceptions = AccountSpecificCacheStorageSettings.defaultSettings.peerStorageTimeoutExceptions
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
var peerStorageTimeoutExceptionsValues: [PeerStorageTimeoutExceptionRepresentation] = []
for value in self.peerStorageTimeoutExceptions {
peerStorageTimeoutExceptionsValues.append(PeerStorageTimeoutExceptionRepresentation(key: value.key, value: value.value))
}
if let data = try? JSONEncoder().encode(peerStorageTimeoutExceptionsValues) {
try container.encode(data, forKey: "peerStorageTimeoutExceptionsJson")
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,469 @@
import Foundation
import Postbox
import TelegramApi
public final class CachedPeerBotInfo: PostboxCoding, Equatable {
public let peerId: PeerId
public let botInfo: BotInfo
public init(peerId: PeerId, botInfo: BotInfo) {
self.peerId = peerId
self.botInfo = botInfo
}
public init(decoder: PostboxDecoder) {
self.peerId = PeerId(decoder.decodeInt64ForKey("p", orElse: 0))
self.botInfo = decoder.decodeObjectForKey("i", decoder: { return BotInfo(decoder: $0) }) as! BotInfo
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.peerId.toInt64(), forKey: "p")
encoder.encodeObject(self.botInfo, forKey: "i")
}
public static func ==(lhs: CachedPeerBotInfo, rhs: CachedPeerBotInfo) -> Bool {
return lhs.peerId == rhs.peerId && lhs.botInfo == rhs.botInfo
}
}
public struct CachedGroupFlags: OptionSet {
public var rawValue: Int32
public init() {
self.rawValue = 0
}
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let canChangeUsername = CachedGroupFlags(rawValue: 1 << 0)
public static let translationHidden = CachedGroupFlags(rawValue: 1 << 1)
}
public enum PeerAllowedReactions: Equatable, Codable {
private enum Discriminant: Int32 {
case all = 0
case limited = 1
case empty = 2
}
case all
case limited([MessageReaction.Reaction])
case empty
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
let discriminant = try container.decode(Int32.self, forKey: "_d")
switch discriminant {
case Discriminant.all.rawValue:
self = .all
case Discriminant.limited.rawValue:
self = .limited(try container.decode([MessageReaction.Reaction].self, forKey: "r"))
case Discriminant.empty.rawValue:
self = .empty
default:
assertionFailure()
self = .all
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self {
case .all:
try container.encode(Discriminant.all.rawValue, forKey: "_d")
case let .limited(reactions):
try container.encode(Discriminant.limited.rawValue, forKey: "_d")
try container.encode(reactions, forKey: "r")
case .empty:
try container.encode(Discriminant.empty.rawValue, forKey: "_d")
}
}
}
extension PeerAllowedReactions {
init(apiReactions: Api.ChatReactions) {
switch apiReactions {
case .chatReactionsAll:
self = .all
case let .chatReactionsSome(reactions):
self = .limited(reactions.compactMap(MessageReaction.Reaction.init(apiReaction:)))
case .chatReactionsNone:
self = .empty
}
}
}
public final class PeerReactionSettings: Equatable, Codable {
public let allowedReactions: PeerAllowedReactions
public let maxReactionCount: Int32?
public let starsAllowed: Bool?
public init(allowedReactions: PeerAllowedReactions, maxReactionCount: Int32?, starsAllowed: Bool?) {
self.allowedReactions = allowedReactions
self.maxReactionCount = maxReactionCount
self.starsAllowed = starsAllowed
}
public static func ==(lhs: PeerReactionSettings, rhs: PeerReactionSettings) -> Bool {
if lhs === rhs {
return true
}
if lhs.allowedReactions != rhs.allowedReactions {
return false
}
if lhs.maxReactionCount != rhs.maxReactionCount {
return false
}
if lhs.starsAllowed != rhs.starsAllowed {
return false
}
return true
}
}
public final class CachedGroupData: CachedPeerData {
public let participants: CachedGroupParticipants?
public let exportedInvitation: ExportedInvitation?
public let botInfos: [CachedPeerBotInfo]
public let peerStatusSettings: PeerStatusSettings?
public let pinnedMessageId: MessageId?
public let about: String?
public let flags: CachedGroupFlags
public let hasScheduledMessages: Bool
public let invitedBy: PeerId?
public let photo: TelegramMediaImage?
public let autoremoveTimeout: CachedPeerAutoremoveTimeout
public let activeCall: CachedChannelData.ActiveCall?
public let callJoinPeerId: PeerId?
public let chatTheme: ChatTheme?
public let inviteRequestsPending: Int32?
public let reactionSettings: EnginePeerCachedInfoItem<PeerReactionSettings>
public let peerIds: Set<PeerId>
public let messageIds: Set<MessageId>
public let associatedHistoryMessageId: MessageId? = nil
public init() {
self.participants = nil
self.exportedInvitation = nil
self.botInfos = []
self.peerStatusSettings = nil
self.pinnedMessageId = nil
self.messageIds = Set()
self.peerIds = Set()
self.about = nil
self.flags = CachedGroupFlags()
self.hasScheduledMessages = false
self.invitedBy = nil
self.photo = nil
self.autoremoveTimeout = .unknown
self.activeCall = nil
self.callJoinPeerId = nil
self.chatTheme = nil
self.inviteRequestsPending = nil
self.reactionSettings = .unknown
}
public init(
participants: CachedGroupParticipants?,
exportedInvitation: ExportedInvitation?,
botInfos: [CachedPeerBotInfo],
peerStatusSettings: PeerStatusSettings?,
pinnedMessageId: MessageId?,
about: String?,
flags: CachedGroupFlags,
hasScheduledMessages: Bool,
invitedBy: PeerId?,
photo: TelegramMediaImage?,
activeCall: CachedChannelData.ActiveCall?,
autoremoveTimeout: CachedPeerAutoremoveTimeout,
callJoinPeerId: PeerId?,
chatTheme: ChatTheme?,
inviteRequestsPending: Int32?,
reactionSettings: EnginePeerCachedInfoItem<PeerReactionSettings>
) {
self.participants = participants
self.exportedInvitation = exportedInvitation
self.botInfos = botInfos
self.peerStatusSettings = peerStatusSettings
self.pinnedMessageId = pinnedMessageId
self.about = about
self.flags = flags
self.hasScheduledMessages = hasScheduledMessages
self.invitedBy = invitedBy
self.photo = photo
self.activeCall = activeCall
self.autoremoveTimeout = autoremoveTimeout
self.callJoinPeerId = callJoinPeerId
self.chatTheme = chatTheme
self.inviteRequestsPending = inviteRequestsPending
self.reactionSettings = reactionSettings
var messageIds = Set<MessageId>()
if let pinnedMessageId = self.pinnedMessageId {
messageIds.insert(pinnedMessageId)
}
self.messageIds = messageIds
var peerIds = Set<PeerId>()
if let participants = participants {
for participant in participants.participants {
peerIds.insert(participant.peerId)
}
}
for botInfo in botInfos {
peerIds.insert(botInfo.peerId)
}
if let invitedBy = invitedBy {
peerIds.insert(invitedBy)
}
self.peerIds = peerIds
}
public init(decoder: PostboxDecoder) {
let participants = decoder.decodeObjectForKey("p", decoder: { CachedGroupParticipants(decoder: $0) }) as? CachedGroupParticipants
self.participants = participants
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, managingBot: nil)
} else if let peerStatusSettings = decoder.decodeObjectForKey("pss", decoder: { PeerStatusSettings(decoder: $0) }) as? PeerStatusSettings {
self.peerStatusSettings = peerStatusSettings
} else {
self.peerStatusSettings = nil
}
if let pinnedMessagePeerId = decoder.decodeOptionalInt64ForKey("pm.p"), let pinnedMessageNamespace = decoder.decodeOptionalInt32ForKey("pm.n"), let pinnedMessageId = decoder.decodeOptionalInt32ForKey("pm.i") {
self.pinnedMessageId = MessageId(peerId: PeerId(pinnedMessagePeerId), namespace: pinnedMessageNamespace, id: pinnedMessageId)
} else {
self.pinnedMessageId = nil
}
self.about = decoder.decodeOptionalStringForKey("ab")
self.flags = CachedGroupFlags(rawValue: decoder.decodeInt32ForKey("fl", orElse: 0))
self.hasScheduledMessages = decoder.decodeBoolForKey("hsm", orElse: false)
self.autoremoveTimeout = decoder.decodeObjectForKey("artv", decoder: CachedPeerAutoremoveTimeout.init(decoder:)) as? CachedPeerAutoremoveTimeout ?? .unknown
self.invitedBy = decoder.decodeOptionalInt64ForKey("invBy").flatMap(PeerId.init)
if let photo = decoder.decodeObjectForKey("ph", decoder: { TelegramMediaImage(decoder: $0) }) as? TelegramMediaImage {
self.photo = photo
} else {
self.photo = nil
}
if let activeCall = decoder.decodeObjectForKey("activeCall", decoder: { CachedChannelData.ActiveCall(decoder: $0) }) as? CachedChannelData.ActiveCall {
self.activeCall = activeCall
} else {
self.activeCall = nil
}
self.callJoinPeerId = decoder.decodeOptionalInt64ForKey("callJoinPeerId").flatMap(PeerId.init)
if let chatThemeData = decoder.decodeDataForKey("ct"), let chatTheme = try? AdaptedPostboxDecoder().decode(ChatTheme.self, from: chatThemeData) {
self.chatTheme = chatTheme
} else if let themeEmoticon = decoder.decodeOptionalStringForKey("te") {
self.chatTheme = .emoticon(themeEmoticon)
} else {
self.chatTheme = nil
}
self.inviteRequestsPending = decoder.decodeOptionalInt32ForKey("irp")
if let reactionSettings = decoder.decode(PeerReactionSettings.self, forKey: "reactionSettings") {
self.reactionSettings = .known(reactionSettings)
} else if let legacyAllowedReactions = decoder.decodeOptionalStringArrayForKey("allowedReactions") {
let allowedReactions: PeerAllowedReactions = .limited(legacyAllowedReactions.map(MessageReaction.Reaction.builtin))
self.reactionSettings = .known(PeerReactionSettings(allowedReactions: allowedReactions, maxReactionCount: nil, starsAllowed: nil))
} else if let allowedReactions = decoder.decode(PeerAllowedReactions.self, forKey: "allowedReactionSet") {
let allowedReactions = allowedReactions
self.reactionSettings = .known(PeerReactionSettings(allowedReactions: allowedReactions, maxReactionCount: nil, starsAllowed: nil))
} else {
self.reactionSettings = .unknown
}
var messageIds = Set<MessageId>()
if let pinnedMessageId = self.pinnedMessageId {
messageIds.insert(pinnedMessageId)
}
self.messageIds = messageIds
var peerIds = Set<PeerId>()
if let participants = participants {
for participant in participants.participants {
peerIds.insert(participant.peerId)
}
}
for botInfo in self.botInfos {
peerIds.insert(botInfo.peerId)
}
self.peerIds = peerIds
}
public func encode(_ encoder: PostboxEncoder) {
if let participants = self.participants {
encoder.encodeObject(participants, forKey: "p")
} else {
encoder.encodeNil(forKey: "p")
}
if let exportedInvitation = self.exportedInvitation {
encoder.encode(exportedInvitation, forKey: "i")
} else {
encoder.encodeNil(forKey: "i")
}
encoder.encodeObjectArray(self.botInfos, forKey: "b")
if let peerStatusSettings = self.peerStatusSettings {
encoder.encodeObject(peerStatusSettings, forKey: "pss")
} else {
encoder.encodeNil(forKey: "pss")
}
if let pinnedMessageId = self.pinnedMessageId {
encoder.encodeInt64(pinnedMessageId.peerId.toInt64(), forKey: "pm.p")
encoder.encodeInt32(pinnedMessageId.namespace, forKey: "pm.n")
encoder.encodeInt32(pinnedMessageId.id, forKey: "pm.i")
} else {
encoder.encodeNil(forKey: "pm.p")
encoder.encodeNil(forKey: "pm.n")
encoder.encodeNil(forKey: "pm.i")
}
if let about = self.about {
encoder.encodeString(about, forKey: "ab")
} else {
encoder.encodeNil(forKey: "ab")
}
encoder.encodeInt32(self.flags.rawValue, forKey: "fl")
encoder.encodeBool(self.hasScheduledMessages, forKey: "hsm")
encoder.encodeObject(self.autoremoveTimeout, forKey: "artv")
if let invitedBy = self.invitedBy {
encoder.encodeInt64(invitedBy.toInt64(), forKey: "invBy")
} else {
encoder.encodeNil(forKey: "invBy")
}
if let photo = self.photo {
encoder.encodeObject(photo, forKey: "ph")
} else {
encoder.encodeNil(forKey: "ph")
}
if let activeCall = self.activeCall {
encoder.encodeObject(activeCall, forKey: "activeCall")
} else {
encoder.encodeNil(forKey: "activeCall")
}
if let callJoinPeerId = self.callJoinPeerId {
encoder.encodeInt64(callJoinPeerId.toInt64(), forKey: "callJoinPeerId")
} else {
encoder.encodeNil(forKey: "callJoinPeerId")
}
if let chatTheme = self.chatTheme, let chatThemeData = try? AdaptedPostboxEncoder().encode(chatTheme) {
encoder.encodeData(chatThemeData, forKey: "ct")
} else {
encoder.encodeNil(forKey: "ct")
}
if let inviteRequestsPending = self.inviteRequestsPending {
encoder.encodeInt32(inviteRequestsPending, forKey: "irp")
} else {
encoder.encodeNil(forKey: "irp")
}
switch self.reactionSettings {
case .unknown:
encoder.encodeNil(forKey: "reactionSettings")
case let .known(value):
encoder.encode(value, forKey: "reactionSettings")
}
}
public func isEqual(to: CachedPeerData) -> Bool {
guard let other = to as? CachedGroupData else {
return false
}
if self.activeCall != other.activeCall {
return false
}
if self.callJoinPeerId != other.callJoinPeerId {
return false
}
if self.reactionSettings != other.reactionSettings {
return false
}
return self.participants == other.participants && self.exportedInvitation == other.exportedInvitation && self.botInfos == other.botInfos && self.peerStatusSettings == other.peerStatusSettings && self.pinnedMessageId == other.pinnedMessageId && self.about == other.about && self.flags == other.flags && self.hasScheduledMessages == other.hasScheduledMessages && self.autoremoveTimeout == other.autoremoveTimeout && self.invitedBy == other.invitedBy && self.chatTheme == other.chatTheme && self.inviteRequestsPending == other.inviteRequestsPending
}
public func withUpdatedParticipants(_ participants: CachedGroupParticipants?) -> CachedGroupData {
return CachedGroupData(participants: participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedExportedInvitation(_ exportedInvitation: ExportedInvitation?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedBotInfos(_ botInfos: [CachedPeerBotInfo]) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedPeerStatusSettings(_ peerStatusSettings: PeerStatusSettings?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedPinnedMessageId(_ pinnedMessageId: MessageId?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedAbout(_ about: String?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedFlags(_ flags: CachedGroupFlags) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedHasScheduledMessages(_ hasScheduledMessages: Bool) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedInvitedBy(_ invitedBy: PeerId?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedPhoto(_ photo: TelegramMediaImage?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedActiveCall(_ activeCall: CachedChannelData.ActiveCall?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedAutoremoveTimeout(_ autoremoveTimeout: CachedPeerAutoremoveTimeout) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedCallJoinPeerId(_ callJoinPeerId: PeerId?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedChatTheme(_ chatTheme: ChatTheme?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedInviteRequestsPending(_ inviteRequestsPending: Int32?) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: inviteRequestsPending, reactionSettings: self.reactionSettings)
}
public func withUpdatedReactionSettings(_ reactionSettings: EnginePeerCachedInfoItem<PeerReactionSettings>) -> CachedGroupData {
return CachedGroupData(participants: self.participants, exportedInvitation: self.exportedInvitation, botInfos: self.botInfos, peerStatusSettings: self.peerStatusSettings, pinnedMessageId: self.pinnedMessageId, about: self.about, flags: self.flags, hasScheduledMessages: self.hasScheduledMessages, invitedBy: self.invitedBy, photo: self.photo, activeCall: self.activeCall, autoremoveTimeout: self.autoremoveTimeout, callJoinPeerId: self.callJoinPeerId, chatTheme: self.chatTheme, inviteRequestsPending: self.inviteRequestsPending, reactionSettings: reactionSettings)
}
}
@@ -0,0 +1,84 @@
import Postbox
public enum GroupParticipant: PostboxCoding, Equatable {
case member(id: PeerId, invitedBy: PeerId, invitedAt: Int32)
case creator(id: PeerId)
case admin(id: PeerId, invitedBy: PeerId, invitedAt: Int32)
public var peerId: PeerId {
switch self {
case let .member(id, _, _):
return id
case let .creator(id):
return id
case let .admin(id, _, _):
return id
}
}
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("v", orElse: 0) {
case 0:
self = .member(id: PeerId(decoder.decodeInt64ForKey("i", orElse: 0)), invitedBy: PeerId(decoder.decodeInt64ForKey("b", orElse: 0)), invitedAt: decoder.decodeInt32ForKey("t", orElse: 0))
case 1:
self = .creator(id: PeerId(decoder.decodeInt64ForKey("i", orElse: 0)))
case 2:
self = .admin(id: PeerId(decoder.decodeInt64ForKey("i", orElse: 0)), invitedBy: PeerId(decoder.decodeInt64ForKey("b", orElse: 0)), invitedAt: decoder.decodeInt32ForKey("t", orElse: 0))
default:
self = .member(id: PeerId(decoder.decodeInt64ForKey("i", orElse: 0)), invitedBy: PeerId(decoder.decodeInt64ForKey("b", orElse: 0)), invitedAt: decoder.decodeInt32ForKey("t", orElse: 0))
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .member(id, invitedBy, invitedAt):
encoder.encodeInt32(0, forKey: "v")
encoder.encodeInt64(id.toInt64(), forKey: "i")
encoder.encodeInt64(invitedBy.toInt64(), forKey: "b")
encoder.encodeInt32(invitedAt, forKey: "t")
case let .creator(id):
encoder.encodeInt32(1, forKey: "v")
encoder.encodeInt64(id.toInt64(), forKey: "i")
case let .admin(id, invitedBy, invitedAt):
encoder.encodeInt32(2, forKey: "v")
encoder.encodeInt64(id.toInt64(), forKey: "i")
encoder.encodeInt64(invitedBy.toInt64(), forKey: "b")
encoder.encodeInt32(invitedAt, forKey: "t")
}
}
public var invitedBy: PeerId {
switch self {
case let .admin(_, invitedBy, _):
return invitedBy
case let .member(_, invitedBy, _):
return invitedBy
case let .creator(id):
return id
}
}
}
public final class CachedGroupParticipants: PostboxCoding, Equatable {
public let participants: [GroupParticipant]
public let version: Int32
public init(participants: [GroupParticipant], version: Int32) {
self.participants = participants
self.version = version
}
public init(decoder: PostboxDecoder) {
self.participants = decoder.decodeObjectArrayWithDecoderForKey("p")
self.version = decoder.decodeInt32ForKey("v", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectArray(self.participants, forKey: "p")
encoder.encodeInt32(self.version, forKey: "v")
}
public static func ==(lhs: CachedGroupParticipants, rhs: CachedGroupParticipants) -> Bool {
return lhs.version == rhs.version && lhs.participants == rhs.participants
}
}
@@ -0,0 +1,21 @@
import Postbox
public final class CachedLocalizationInfos: Codable {
public let list: [LocalizationInfo]
public init(list: [LocalizationInfo]) {
self.list = list
}
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(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.list, forKey: "t")
}
}
@@ -0,0 +1,30 @@
import Postbox
public final class CachedRecentPeers: Codable {
public let enabled: Bool
public let ids: [PeerId]
public init(enabled: Bool, ids: [PeerId]) {
self.enabled = enabled
self.ids = ids
}
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(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 {
let key = ValueBoxKey(length: 0)
return key
}
}
@@ -0,0 +1,41 @@
import Foundation
import Postbox
public final class CachedResolvedByNamePeer: Codable {
public let peerId: PeerId?
public let timestamp: Int32
public static func key(name: String) -> ValueBoxKey {
let key: ValueBoxKey
if let nameData = name.data(using: .utf8) {
key = ValueBoxKey(length: nameData.count)
nameData.withUnsafeBytes { rawBytes -> Void in
let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self)
memcpy(key.memory, bytes, nameData.count)
}
} else {
key = ValueBoxKey(length: 0)
}
return key
}
public init(peerId: PeerId?, timestamp: Int32) {
self.peerId = peerId
self.timestamp = timestamp
}
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(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")
}
}
@@ -0,0 +1,41 @@
import Foundation
import Postbox
public final class CachedResolvedByPhonePeer: Codable {
public let peerId: PeerId?
public let timestamp: Int32
public static func key(name: String) -> ValueBoxKey {
let key: ValueBoxKey
if let nameData = name.data(using: .utf8) {
key = ValueBoxKey(length: nameData.count)
nameData.withUnsafeBytes { rawBytes -> Void in
let bytes = rawBytes.baseAddress!.assumingMemoryBound(to: Int8.self)
memcpy(key.memory, bytes, nameData.count)
}
} else {
key = ValueBoxKey(length: 0)
}
return key
}
public init(peerId: PeerId?, timestamp: Int32) {
self.peerId = peerId
self.timestamp = timestamp
}
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(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")
}
}
@@ -0,0 +1,48 @@
import Foundation
import Postbox
public struct SecureIdConfiguration: Codable {
public let nativeLanguageByCountry: [String: String]
public init(jsonString: String) {
self.nativeLanguageByCountry = (try? JSONDecoder().decode(Dictionary<String, String>.self, from: jsonString.data(using: .utf8) ?? Data())) ?? [:]
}
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<String, String>.self, from: nativeLanguageByCountryData)) ?? [:]
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
let nativeLanguageByCountryData = (try? JSONEncoder().encode(self.nativeLanguageByCountry)) ?? Data()
try container.encode(nativeLanguageByCountryData, forKey: "nativeLanguageByCountry")
}
}
public final class CachedSecureIdConfiguration: Codable {
public let value: SecureIdConfiguration
public let hash: Int32
public init(value: SecureIdConfiguration, hash: Int32) {
self.value = value
self.hash = hash
}
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(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")
}
}
@@ -0,0 +1,73 @@
import Foundation
import Postbox
import FlatBuffers
import FlatSerialization
public final class CachedStickerPack: Codable {
public let info: StickerPackCollectionInfo.Accessor?
public let items: [StickerPackItem]
public let hash: Int32
public init(info: StickerPackCollectionInfo?, items: [StickerPackItem], hash: Int32) {
self.info = info.flatMap(StickerPackCollectionInfo.Accessor.init)
self.items = items
self.hash = hash
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let serializedInfoData = try container.decodeIfPresent(Data.self, forKey: "ind") {
var byteBuffer = ByteBuffer(data: serializedInfoData)
self.info = StickerPackCollectionInfo.Accessor(FlatBuffers_getRoot(byteBuffer: &byteBuffer) as TelegramCore_StickerPackCollectionInfo, serializedInfoData)
} else if let infoData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "in") {
let info = StickerPackCollectionInfo(decoder: PostboxDecoder(buffer: MemoryBuffer(data: infoData.data)))
self.info = StickerPackCollectionInfo.Accessor(info)
} 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(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
if let info = self.info {
if let infoData = info._wrappedData {
try container.encode(infoData, forKey: "ind")
} else if let info = info._wrappedObject {
var builder = FlatBufferBuilder(initialSize: 1024)
let value = info.encodeToFlatBuffers(builder: &builder)
builder.finish(offset: value)
let serializedInstantPage = builder.data
try container.encode(serializedInstantPage, forKey: "ind")
} else {
preconditionFailure()
}
} else {
try container.encodeNil(forKey: "in")
}
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 {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: id.namespace)
key.setInt64(4, value: id.id)
return key
}
public static func cacheKey(shortName: String) -> ValueBoxKey {
return ValueBoxKey(shortName)
}
}
@@ -0,0 +1,39 @@
import Postbox
public final class CachedStickerQueryResult: Codable {
public let items: [TelegramMediaFile]
public let hash: Int64
public let timestamp: Int32
public init(items: [TelegramMediaFile], hash: Int64, timestamp: Int32) {
self.items = items
self.hash = hash
self.timestamp = timestamp
}
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(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 {
let key = ValueBoxKey(query)
return key
}
}
@@ -0,0 +1,21 @@
import Postbox
public final class CachedThemesConfiguration: Codable {
public let hash: Int64
public init(hash: Int64) {
self.hash = hash
}
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(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.hash, forKey: "hash6")
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,21 @@
import Postbox
public final class CachedWallpapersConfiguration: Codable {
public let hash: Int64
public init(hash: Int64) {
self.hash = hash
}
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(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.hash, forKey: "hash6")
}
}
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class ChannelMessageStateVersionAttribute: MessageAttribute {
public let pts: Int32
public init(pts: Int32) {
self.pts = pts
}
required public init(decoder: PostboxDecoder) {
self.pts = decoder.decodeInt32ForKey("p", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.pts, forKey: "p")
}
}
@@ -0,0 +1,60 @@
import Postbox
public final class ChannelState: PeerChatState, Equatable, CustomStringConvertible {
public let pts: Int32
public let invalidatedPts: Int32?
public let synchronizedUntilMessageId: Int32?
public init(pts: Int32, invalidatedPts: Int32?, synchronizedUntilMessageId: Int32?) {
self.pts = pts
self.invalidatedPts = invalidatedPts
self.synchronizedUntilMessageId = synchronizedUntilMessageId
}
public init(decoder: PostboxDecoder) {
self.pts = decoder.decodeInt32ForKey("pts", orElse: 0)
self.invalidatedPts = decoder.decodeOptionalInt32ForKey("ipts")
self.synchronizedUntilMessageId = decoder.decodeOptionalInt32ForKey("sumi")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.pts, forKey: "pts")
if let invalidatedPts = self.invalidatedPts {
encoder.encodeInt32(invalidatedPts, forKey: "ipts")
} else {
encoder.encodeNil(forKey: "ipts")
}
if let synchronizedUntilMessageId = self.synchronizedUntilMessageId {
encoder.encodeInt32(synchronizedUntilMessageId, forKey: "sumi")
} else {
encoder.encodeNil(forKey: "sumi")
}
}
public func withUpdatedPts(_ pts: Int32) -> ChannelState {
return ChannelState(pts: pts, invalidatedPts: self.invalidatedPts, synchronizedUntilMessageId: self.synchronizedUntilMessageId)
}
public func withUpdatedInvalidatedPts(_ invalidatedPts: Int32?) -> ChannelState {
return ChannelState(pts: self.pts, invalidatedPts: invalidatedPts, synchronizedUntilMessageId: self.synchronizedUntilMessageId)
}
public func withUpdatedSynchronizedUntilMessageId(_ synchronizedUntilMessageId: Int32?) -> ChannelState {
return ChannelState(pts: self.pts, invalidatedPts: self.invalidatedPts, synchronizedUntilMessageId: synchronizedUntilMessageId)
}
public func equals(_ other: PeerChatState) -> Bool {
if let other = other as? ChannelState, other == self {
return true
}
return false
}
public var description: String {
return "(pts: \(self.pts), invalidatedPts: \(String(describing: self.invalidatedPts)), synchronizedUntilMessageId: \(String(describing: self.synchronizedUntilMessageId))"
}
public static func ==(lhs: ChannelState, rhs: ChannelState) -> Bool {
return lhs.pts == rhs.pts && lhs.invalidatedPts == rhs.invalidatedPts && lhs.synchronizedUntilMessageId == rhs.synchronizedUntilMessageId
}
}
@@ -0,0 +1,169 @@
import Foundation
import Postbox
public enum InteractiveMessagesDeletionType: Int32 {
case forLocalPeer = 0
case forEveryone = 1
}
public enum CloudChatRemoveMessagesType: Int32 {
case forLocalPeer
case forEveryone
}
public extension CloudChatRemoveMessagesType {
init(_ type: InteractiveMessagesDeletionType) {
switch type {
case .forLocalPeer:
self = .forLocalPeer
case .forEveryone:
self = .forEveryone
}
}
}
public final class CloudChatRemoveMessagesOperation: PostboxCoding {
public let messageIds: [MessageId]
public let threadId: Int64?
public let type: CloudChatRemoveMessagesType
public init(messageIds: [MessageId], threadId: Int64?, type: CloudChatRemoveMessagesType) {
self.messageIds = messageIds
self.threadId = threadId
self.type = type
}
public init(decoder: PostboxDecoder) {
self.messageIds = MessageId.decodeArrayFromBuffer(decoder.decodeBytesForKeyNoCopy("i")!)
self.threadId = decoder.decodeOptionalInt64ForKey("threadId")
self.type = CloudChatRemoveMessagesType(rawValue: decoder.decodeInt32ForKey("t", orElse: 0))!
}
public func encode(_ encoder: PostboxEncoder) {
let buffer = WriteBuffer()
MessageId.encodeArrayToBuffer(self.messageIds, buffer: buffer)
if let threadId = self.threadId {
encoder.encodeInt64(threadId, forKey: "threadId")
} else {
encoder.encodeNil(forKey: "threadId")
}
encoder.encodeBytes(buffer, forKey: "i")
encoder.encodeInt32(self.type.rawValue, forKey: "t")
}
}
public final class CloudChatRemoveChatOperation: PostboxCoding {
public let peerId: PeerId
public let reportChatSpam: Bool
public let deleteGloballyIfPossible: Bool
public let topMessageId: MessageId?
public init(peerId: PeerId, reportChatSpam: Bool, deleteGloballyIfPossible: Bool, topMessageId: MessageId?) {
self.peerId = peerId
self.reportChatSpam = reportChatSpam
self.deleteGloballyIfPossible = deleteGloballyIfPossible
self.topMessageId = topMessageId
}
public init(decoder: PostboxDecoder) {
self.peerId = PeerId(decoder.decodeInt64ForKey("p", orElse: 0))
self.reportChatSpam = decoder.decodeInt32ForKey("r", orElse: 0) != 0
self.deleteGloballyIfPossible = decoder.decodeInt32ForKey("deleteGloballyIfPossible", orElse: 0) != 0
if let messageIdPeerId = decoder.decodeOptionalInt64ForKey("m.p"), let messageIdNamespace = decoder.decodeOptionalInt32ForKey("m.n"), let messageIdId = decoder.decodeOptionalInt32ForKey("m.i") {
self.topMessageId = MessageId(peerId: PeerId(messageIdPeerId), namespace: messageIdNamespace, id: messageIdId)
} else {
self.topMessageId = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.peerId.toInt64(), forKey: "p")
encoder.encodeInt32(self.reportChatSpam ? 1 : 0, forKey: "r")
encoder.encodeInt32(self.deleteGloballyIfPossible ? 1 : 0, forKey: "deleteGloballyIfPossible")
if let topMessageId = self.topMessageId {
encoder.encodeInt64(topMessageId.peerId.toInt64(), forKey: "m.p")
encoder.encodeInt32(topMessageId.namespace, forKey: "m.n")
encoder.encodeInt32(topMessageId.id, forKey: "m.i")
} else {
encoder.encodeNil(forKey: "m.p")
encoder.encodeNil(forKey: "m.n")
encoder.encodeNil(forKey: "m.i")
}
}
}
public enum CloudChatClearHistoryType: Int32 {
case forLocalPeer
case forEveryone
case scheduledMessages
case quickReplyMessages
}
public enum InteractiveHistoryClearingType: Int32 {
case forLocalPeer = 0
case forEveryone = 1
case scheduledMessages = 2
}
public extension CloudChatClearHistoryType {
init(_ type: InteractiveHistoryClearingType) {
switch type {
case .forLocalPeer:
self = .forLocalPeer
case .forEveryone:
self = .forEveryone
case .scheduledMessages:
self = .scheduledMessages
}
}
}
public final class CloudChatClearHistoryOperation: PostboxCoding {
public let peerId: PeerId
public let topMessageId: MessageId
public let threadId: Int64?
public let minTimestamp: Int32?
public let maxTimestamp: Int32?
public let type: CloudChatClearHistoryType
public init(peerId: PeerId, topMessageId: MessageId, threadId: Int64?, minTimestamp: Int32?, maxTimestamp: Int32?, type: CloudChatClearHistoryType) {
self.peerId = peerId
self.topMessageId = topMessageId
self.threadId = threadId
self.minTimestamp = minTimestamp
self.maxTimestamp = maxTimestamp
self.type = type
}
public init(decoder: PostboxDecoder) {
self.peerId = PeerId(decoder.decodeInt64ForKey("p", orElse: 0))
self.topMessageId = MessageId(peerId: PeerId(decoder.decodeInt64ForKey("m.p", orElse: 0)), namespace: decoder.decodeInt32ForKey("m.n", orElse: 0), id: decoder.decodeInt32ForKey("m.i", orElse: 0))
self.threadId = decoder.decodeOptionalInt64ForKey("threadId")
self.minTimestamp = decoder.decodeOptionalInt32ForKey("minTimestamp")
self.maxTimestamp = decoder.decodeOptionalInt32ForKey("maxTimestamp")
self.type = CloudChatClearHistoryType(rawValue: decoder.decodeInt32ForKey("type", orElse: 0)) ?? .forLocalPeer
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.peerId.toInt64(), forKey: "p")
encoder.encodeInt64(self.topMessageId.peerId.toInt64(), forKey: "m.p")
encoder.encodeInt32(self.topMessageId.namespace, forKey: "m.n")
encoder.encodeInt32(self.topMessageId.id, forKey: "m.i")
if let threadId = self.threadId {
encoder.encodeInt64(threadId, forKey: "threadId")
} else {
encoder.encodeNil(forKey: "threadId")
}
if let minTimestamp = self.minTimestamp {
encoder.encodeInt32(minTimestamp, forKey: "minTimestamp")
} else {
encoder.encodeNil(forKey: "minTimestamp")
}
if let maxTimestamp = self.maxTimestamp {
encoder.encodeInt32(maxTimestamp, forKey: "maxTimestamp")
} else {
encoder.encodeNil(forKey: "maxTimestamp")
}
encoder.encodeInt32(self.type.rawValue, forKey: "type")
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class ConsumableContentMessageAttribute: MessageAttribute {
public let consumed: Bool
public init(consumed: Bool) {
self.consumed = consumed
}
required public init(decoder: PostboxDecoder) {
self.consumed = decoder.decodeInt32ForKey("c", orElse: 0) != 0
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.consumed ? 1 : 0, forKey: "c")
}
}
@@ -0,0 +1,22 @@
import Foundation
import Postbox
public class ConsumablePersonalMentionMessageAttribute: MessageAttribute {
public let consumed: Bool
public let pending: Bool
public init(consumed: Bool, pending: Bool) {
self.consumed = consumed
self.pending = pending
}
required public init(decoder: PostboxDecoder) {
self.consumed = decoder.decodeInt32ForKey("c", orElse: 0) != 0
self.pending = decoder.decodeInt32ForKey("p", orElse: 0) != 0
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.consumed ? 1 : 0, forKey: "c")
encoder.encodeInt32(self.pending ? 1 : 0, forKey: "p")
}
}
@@ -0,0 +1,40 @@
import Foundation
import Postbox
public final class ConsumePersonalMessageAction: PendingMessageActionData {
public init() {
}
public init(decoder: PostboxDecoder) {
}
public func encode(_ encoder: PostboxEncoder) {
}
public func isEqual(to: PendingMessageActionData) -> Bool {
if let _ = to as? ConsumePersonalMessageAction {
return true
} else {
return false
}
}
}
public final class ReadReactionAction: PendingMessageActionData {
public init() {
}
public init(decoder: PostboxDecoder) {
}
public func encode(_ encoder: PostboxEncoder) {
}
public func isEqual(to: PendingMessageActionData) -> Bool {
if let _ = to as? ReadReactionAction {
return true
} else {
return false
}
}
}
@@ -0,0 +1,26 @@
import Foundation
import Postbox
public struct ContactsSettings: Codable {
public var synchronizeContacts: Bool
public static var defaultSettings: ContactsSettings {
return ContactsSettings(synchronizeContacts: true)
}
public init(synchronizeContacts: Bool) {
self.synchronizeContacts = synchronizeContacts
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.synchronizeContacts = ((try? container.decode(Int32.self, forKey: "synchronizeContacts")) ?? 0) != 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode((self.synchronizeContacts ? 1 : 0) as Int32, forKey: "synchronizeContacts")
}
}
@@ -0,0 +1,35 @@
import Postbox
public final class ContentPrivacySettings: Codable {
public let enableSecretChatWebpagePreviews: Bool?
public static var defaultSettings = ContentPrivacySettings(enableSecretChatWebpagePreviews: nil)
public init(enableSecretChatWebpagePreviews: Bool?) {
self.enableSecretChatWebpagePreviews = enableSecretChatWebpagePreviews
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let value = try? container.decodeIfPresent(Int32.self, forKey: "enableSecretChatWebpagePreviews") {
self.enableSecretChatWebpagePreviews = value != 0
} else {
self.enableSecretChatWebpagePreviews = nil
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
if let enableSecretChatWebpagePreviews = self.enableSecretChatWebpagePreviews {
try container.encode((enableSecretChatWebpagePreviews ? 1 : 0) as Int32, forKey: "enableSecretChatWebpagePreviews")
} else {
try container.encodeNil(forKey: "enableSecretChatWebpagePreviews")
}
}
public func withUpdatedEnableSecretChatWebpagePreviews(_ enableSecretChatWebpagePreviews: Bool) -> ContentPrivacySettings {
return ContentPrivacySettings(enableSecretChatWebpagePreviews: enableSecretChatWebpagePreviews)
}
}
@@ -0,0 +1,13 @@
import Foundation
import Postbox
public class ContentRequiresValidationMessageAttribute: MessageAttribute {
public init() {
}
required public init(decoder: PostboxDecoder) {
}
public func encode(_ encoder: PostboxEncoder) {
}
}
@@ -0,0 +1,23 @@
import Foundation
import Postbox
public class EditedMessageAttribute: MessageAttribute {
public let date: Int32
public let isHidden: Bool
public init(date: Int32, isHidden: Bool) {
self.date = date
self.isHidden = isHidden
}
required public init(decoder: PostboxDecoder) {
self.date = decoder.decodeInt32ForKey("d", orElse: 0)
self.isHidden = decoder.decodeInt32ForKey("h", orElse: 0) != 0
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.date, forKey: "d")
encoder.encodeInt32(self.isHidden ? 1 : 0, forKey: "h")
}
}
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class EffectMessageAttribute: MessageAttribute {
public let id: Int64
public init(id: Int64) {
self.id = id
}
required public init(decoder: PostboxDecoder) {
self.id = decoder.decodeInt64ForKey("id", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.id, forKey: "id")
}
}
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class EmbeddedMediaStickersMessageAttribute: MessageAttribute {
public let files: [TelegramMediaFile]
public init(files: [TelegramMediaFile]) {
self.files = files
}
required public init(decoder: PostboxDecoder) {
self.files = decoder.decodeObjectArrayWithDecoderForKey("files")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectArray(self.files, forKey: "files")
}
}
@@ -0,0 +1,57 @@
import Postbox
public func emojiKeywordColletionIdForCode(_ code: String) -> ItemCollectionId {
return ItemCollectionId(namespace: Namespaces.ItemCollection.EmojiKeywords, id: Int64(HashFunctions.murMurHash32(code)))
}
public final class EmojiKeywordCollectionInfo: ItemCollectionInfo, Equatable {
public let id: ItemCollectionId
public let languageCode: String
public let inputLanguageCode: String
public let version: Int32
public let timestamp: Int32
public init(languageCode: String, inputLanguageCode: String, version: Int32, timestamp: Int32) {
self.id = emojiKeywordColletionIdForCode(inputLanguageCode)
self.languageCode = languageCode
self.inputLanguageCode = inputLanguageCode
self.version = version
self.timestamp = timestamp
}
public init(decoder: PostboxDecoder) {
self.id = ItemCollectionId(namespace: decoder.decodeInt32ForKey("i.n", orElse: 0), id: decoder.decodeInt64ForKey("i.i", orElse: 0))
self.languageCode = decoder.decodeStringForKey("lc", orElse: "")
self.inputLanguageCode = decoder.decodeStringForKey("ilc", orElse: "")
self.version = decoder.decodeInt32ForKey("v", orElse: 0)
self.timestamp = decoder.decodeInt32ForKey("t", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.id.namespace, forKey: "i.n")
encoder.encodeInt64(self.id.id, forKey: "i.i")
encoder.encodeString(self.languageCode, forKey: "lc")
encoder.encodeString(self.inputLanguageCode, forKey: "ilc")
encoder.encodeInt32(self.version, forKey: "v")
encoder.encodeInt32(self.timestamp, forKey: "t")
}
public static func ==(lhs: EmojiKeywordCollectionInfo, rhs: EmojiKeywordCollectionInfo) -> Bool {
if lhs.id != rhs.id {
return false
}
if lhs.languageCode != rhs.languageCode {
return false
}
if lhs.inputLanguageCode != rhs.inputLanguageCode {
return false
}
if lhs.version != rhs.version {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
return true
}
}
@@ -0,0 +1,38 @@
import Postbox
public final class EmojiKeywordItem: ItemCollectionItem, Equatable {
public let index: ItemCollectionItemIndex
public let collectionId: ItemCollectionId.Id
public let keyword: String
public let emoticons: [String]
public let indexKeys: [MemoryBuffer]
public init(index: ItemCollectionItemIndex, collectionId: ItemCollectionId.Id, keyword: String, emoticons: [String], indexKeys: [MemoryBuffer]) {
self.index = index
self.collectionId = collectionId
self.keyword = keyword
self.emoticons = emoticons
self.indexKeys = indexKeys
}
public init(decoder: PostboxDecoder) {
self.index = ItemCollectionItemIndex(index: decoder.decodeInt32ForKey("i.n", orElse: 0), id: decoder.decodeInt64ForKey("i.i", orElse: 0))
self.collectionId = decoder.decodeInt64ForKey("c", orElse: 0)
self.keyword = decoder.decodeStringForKey("k", orElse: "")
self.emoticons = decoder.decodeStringArrayForKey("e")
self.indexKeys = decoder.decodeBytesArrayForKey("s")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.index.index, forKey: "i.n")
encoder.encodeInt64(self.index.id, forKey: "i.i")
encoder.encodeInt64(self.collectionId, forKey: "c")
encoder.encodeString(self.keyword, forKey: "k")
encoder.encodeStringArray(self.emoticons, forKey: "e")
encoder.encodeBytesArray(self.indexKeys, forKey: "s")
}
public static func ==(lhs: EmojiKeywordItem, rhs: EmojiKeywordItem) -> Bool {
return lhs.index == rhs.index && lhs.collectionId == rhs.collectionId && lhs.keyword == rhs.keyword && lhs.emoticons == rhs.emoticons && lhs.indexKeys == rhs.indexKeys
}
}
@@ -0,0 +1,20 @@
import Foundation
import Postbox
public class EmojiSearchQueryMessageAttribute: MessageAttribute {
public let query: String
public var associatedMessageIds: [MessageId] = []
public init(query: String) {
self.query = query
}
required public init(decoder: PostboxDecoder) {
self.query = decoder.decodeStringForKey("q", orElse: "")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.query, forKey: "q")
}
}
@@ -0,0 +1,83 @@
import Postbox
public enum ExportedInvitation: Codable, Equatable {
case link(link: String, title: String?, isPermanent: Bool, requestApproval: Bool, isRevoked: Bool, adminId: PeerId, date: Int32, startDate: Int32?, expireDate: Int32?, usageLimit: Int32?, count: Int32?, requestedCount: Int32?, pricing: StarsSubscriptionPricing?)
case publicJoinRequest
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
let type = try container.decodeIfPresent(Int32.self, forKey: "t") ?? 0
if type == 0 {
let link = try container.decode(String.self, forKey: "l")
let title = try container.decodeIfPresent(String.self, forKey: "title")
let isPermanent = try container.decode(Bool.self, forKey: "permanent")
let requestApproval = try container.decodeIfPresent(Bool.self, forKey: "requestApproval") ?? false
let isRevoked = try container.decode(Bool.self, forKey: "revoked")
let adminId = PeerId(try container.decode(Int64.self, forKey: "adminId"))
let date = try container.decode(Int32.self, forKey: "date")
let startDate = try container.decodeIfPresent(Int32.self, forKey: "startDate")
let expireDate = try container.decodeIfPresent(Int32.self, forKey: "expireDate")
let usageLimit = try container.decodeIfPresent(Int32.self, forKey: "usageLimit")
let count = try container.decodeIfPresent(Int32.self, forKey: "count")
let requestedCount = try? container.decodeIfPresent(Int32.self, forKey: "requestedCount")
let pricing = try? container.decodeIfPresent(StarsSubscriptionPricing.self, forKey: "pricing")
self = .link(link: link, title: title, isPermanent: isPermanent, requestApproval: requestApproval, isRevoked: isRevoked, adminId: adminId, date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: count, requestedCount: requestedCount, pricing: pricing)
} else {
self = .publicJoinRequest
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self {
case let .link(link, title, isPermanent, requestApproval, isRevoked, adminId, date, startDate, expireDate, usageLimit, count, requestedCount, pricing):
let type: Int32 = 0
try container.encode(type, forKey: "t")
try container.encode(link, forKey: "l")
try container.encodeIfPresent(title, forKey: "title")
try container.encode(isPermanent, forKey: "permanent")
try container.encode(requestApproval, forKey: "requestApproval")
try container.encode(isRevoked, forKey: "revoked")
try container.encode(adminId.toInt64(), forKey: "adminId")
try container.encode(date, forKey: "date")
try container.encodeIfPresent(startDate, forKey: "startDate")
try container.encodeIfPresent(expireDate, forKey: "expireDate")
try container.encodeIfPresent(usageLimit, forKey: "usageLimit")
try container.encodeIfPresent(count, forKey: "count")
try container.encodeIfPresent(requestedCount, forKey: "requestedCount")
try container.encodeIfPresent(pricing, forKey: "pricing")
case .publicJoinRequest:
let type: Int32 = 1
try container.encode(type, forKey: "t")
}
}
public static func ==(lhs: ExportedInvitation, rhs: ExportedInvitation) -> Bool {
switch lhs {
case let .link(link, title, isPermanent, requestApproval, isRevoked, adminId, date, startDate, expireDate, usageLimit, count, requestedCount, pricing):
if case .link(link, title, isPermanent, requestApproval, isRevoked, adminId, date, startDate, expireDate, usageLimit, count, requestedCount, pricing) = rhs {
return true
} else {
return false
}
case .publicJoinRequest:
if case .publicJoinRequest = rhs {
return true
} else {
return false
}
}
}
public func withUpdated(isRevoked: Bool) -> ExportedInvitation {
switch self {
case let .link(link, title, isPermanent, requestApproval, _, adminId, date, startDate, expireDate, usageLimit, count, requestedCount, pricing):
return .link(link: link, title: title, isPermanent: isPermanent, requestApproval: requestApproval, isRevoked: isRevoked, adminId: adminId, date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: count, requestedCount: requestedCount, pricing: pricing)
case .publicJoinRequest:
return .publicJoinRequest
}
}
}
@@ -0,0 +1,73 @@
import Postbox
public class FactCheckMessageAttribute: MessageAttribute, Equatable {
public enum Content: PostboxCoding, Equatable {
case Pending
case Loaded(text: String, entities: [MessageTextEntity], country: String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("_v", orElse: 0) {
case 0:
self = .Pending
case 1:
self = .Loaded(
text: decoder.decodeStringForKey("text", orElse: ""),
entities: decoder.decodeObjectArrayWithDecoderForKey("entities"),
country: decoder.decodeStringForKey("country", orElse: "")
)
default:
assertionFailure()
self = .Pending
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .Pending:
encoder.encodeInt32(0, forKey: "_v")
case let .Loaded(text, entities, country):
encoder.encodeInt32(1, forKey: "_v")
encoder.encodeString(text, forKey: "text")
encoder.encodeObjectArray(entities, forKey: "entities")
encoder.encodeString(country, forKey: "country")
}
}
}
public let content: Content
public let hash: Int64
public var associatedPeerIds: [PeerId] {
return []
}
public init(
content: Content,
hash: Int64
) {
self.content = content
self.hash = hash
}
required public init(decoder: PostboxDecoder) {
self.content = decoder.decodeObjectForKey("content", decoder: { FactCheckMessageAttribute.Content(decoder: $0) }) as! FactCheckMessageAttribute.Content
self.hash = decoder.decodeInt64ForKey("hash", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObject(self.content, forKey: "content")
encoder.encodeInt64(self.hash, forKey: "hash")
}
public static func ==(lhs: FactCheckMessageAttribute, rhs: FactCheckMessageAttribute) -> Bool {
if lhs.content != rhs.content {
return false
}
if lhs.hash != rhs.hash {
return false
}
return true
}
}
@@ -0,0 +1,75 @@
import Foundation
import Postbox
import FlatBuffers
import FlatSerialization
public struct FeaturedStickerPackItemId {
public let rawValue: MemoryBuffer
public let packId: Int64
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length == 8)
var idValue: Int64 = 0
memcpy(&idValue, rawValue.memory, 8)
self.packId = idValue
}
public init(_ packId: Int64) {
self.packId = packId
var idValue: Int64 = packId
self.rawValue = MemoryBuffer(memory: malloc(8)!, capacity: 8, length: 8, freeWhenDone: true)
memcpy(self.rawValue.memory, &idValue, 8)
}
}
public final class FeaturedStickerPackItem: Codable {
public let info: StickerPackCollectionInfo.Accessor
public let topItems: [StickerPackItem]
public let unread: Bool
public init(info: StickerPackCollectionInfo.Accessor, topItems: [StickerPackItem], unread: Bool) {
self.info = info
self.topItems = topItems
self.unread = unread
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let serializedInfoData = try container.decodeIfPresent(Data.self, forKey: "infd") {
var byteBuffer = ByteBuffer(data: serializedInfoData)
self.info = StickerPackCollectionInfo.Accessor(FlatBuffers_getRoot(byteBuffer: &byteBuffer) as TelegramCore_StickerPackCollectionInfo, serializedInfoData)
} else {
let infoData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "i")
self.info = StickerPackCollectionInfo.Accessor(StickerPackCollectionInfo(decoder: PostboxDecoder(buffer: MemoryBuffer(data: infoData.data))))
}
self.topItems = (try container.decode([AdaptedPostboxDecoder.RawObjectData].self, forKey: "t")).map { itemData in
return StickerPackItem(decoder: PostboxDecoder(buffer: MemoryBuffer(data: itemData.data)))
}
self.unread = try container.decode(Int32.self, forKey: "u") != 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
if let infoData = self.info._wrappedData {
try container.encode(infoData, forKey: "infd")
} else if let info = self.info._wrappedObject {
var builder = FlatBufferBuilder(initialSize: 1024)
let value = info.encodeToFlatBuffers(builder: &builder)
builder.finish(offset: value)
let serializedInstantPage = builder.data
try container.encode(serializedInstantPage, forKey: "infd")
} else {
preconditionFailure()
}
try container.encode(self.topItems.map { item in
return PostboxEncoder().encodeObjectToRawData(item)
}, forKey: "t")
try container.encode((self.unread ? 1 : 0) as Int32, forKey: "u")
}
}
@@ -0,0 +1,22 @@
import Postbox
public final class FeaturedStickersConfiguration: Codable {
public let isPremium: Bool
public init(isPremium: Bool) {
self.isPremium = isPremium
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.isPremium = try container.decode(Bool.self, forKey: "isPremium")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.isPremium, forKey: "isPremium")
}
}
@@ -0,0 +1,20 @@
import Foundation
import Postbox
public class ForwardCountMessageAttribute: MessageAttribute {
public let count: Int
public var associatedMessageIds: [MessageId] = []
public init(count: Int) {
self.count = count
}
required public init(decoder: PostboxDecoder) {
self.count = Int(decoder.decodeInt32ForKey("c", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(Int32(self.count), forKey: "c")
}
}
@@ -0,0 +1,22 @@
import Foundation
import Postbox
public class ForwardOptionsMessageAttribute: MessageAttribute {
public let hideNames: Bool
public let hideCaptions: Bool
public init(hideNames: Bool, hideCaptions: Bool) {
self.hideNames = hideNames
self.hideCaptions = hideCaptions
}
required public init(decoder: PostboxDecoder) {
self.hideNames = decoder.decodeBoolForKey("hideNames", orElse: false)
self.hideCaptions = decoder.decodeBoolForKey("hideCaptions", orElse: false)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeBool(self.hideNames, forKey: "hideNames")
encoder.encodeBool(self.hideCaptions, forKey: "hideCaptions")
}
}
@@ -0,0 +1,20 @@
import Foundation
import Postbox
public class ForwardSourceInfoAttribute: MessageAttribute {
public let messageId: MessageId
public init(messageId: MessageId) {
self.messageId = messageId
}
required public init(decoder: PostboxDecoder) {
self.messageId = MessageId(peerId: PeerId(decoder.decodeInt64ForKey("p", orElse: 0)), namespace: decoder.decodeInt32ForKey("n", orElse: 0), id: decoder.decodeInt32ForKey("i", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.messageId.peerId.toInt64(), forKey: "p")
encoder.encodeInt32(self.messageId.namespace, forKey: "n")
encoder.encodeInt32(self.messageId.id, forKey: "i")
}
}
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class ForwardVideoTimestampAttribute: MessageAttribute {
public let timestamp: Int32
public init(timestamp: Int32) {
self.timestamp = timestamp
}
required public init(decoder: PostboxDecoder) {
self.timestamp = decoder.decodeInt32ForKey("timestamp", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.timestamp, forKey: "timestamp")
}
}
@@ -0,0 +1,160 @@
import Postbox
public struct MessageNotificationSettings: Codable, Equatable {
public var enabled: Bool
public var displayPreviews: Bool
public var sound: PeerMessageSound
public var storySettings: PeerStoryNotificationSettings
public static var defaultSettings: MessageNotificationSettings {
return MessageNotificationSettings(enabled: true, displayPreviews: true, sound: defaultCloudPeerNotificationSound, storySettings: PeerStoryNotificationSettings.default)
}
public init(enabled: Bool, displayPreviews: Bool, sound: PeerMessageSound, storySettings: PeerStoryNotificationSettings) {
self.enabled = enabled
self.displayPreviews = displayPreviews
self.sound = sound
self.storySettings = storySettings
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.enabled = ((try? container.decode(Int32.self, forKey: "e")) ?? 0) != 0
self.displayPreviews = ((try? container.decode(Int32.self, forKey: "p")) ?? 0) != 0
self.sound = try PeerMessageSound.decodeInline(container)
self.storySettings = try container.decodeIfPresent(PeerStoryNotificationSettings.self, forKey: "stor") ?? PeerStoryNotificationSettings(mute: .unmuted, hideSender: .show, sound: defaultCloudPeerNotificationSound)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode((self.enabled ? 1 : 0) as Int32, forKey: "e")
try container.encode((self.displayPreviews ? 1 : 0) as Int32, forKey: "p")
try self.sound.encodeInline(&container)
try container.encode(self.storySettings, forKey: "stor")
}
}
public struct GlobalNotificationSettingsSet: Codable, Equatable {
public var privateChats: MessageNotificationSettings
public var groupChats: MessageNotificationSettings
public var channels: MessageNotificationSettings
public var reactionSettings: PeerReactionNotificationSettings
public var contactsJoined: Bool
public static var defaultSettings: GlobalNotificationSettingsSet {
return GlobalNotificationSettingsSet(privateChats: MessageNotificationSettings.defaultSettings, groupChats: .defaultSettings, channels: .defaultSettings, reactionSettings: .default, contactsJoined: true)
}
public init(privateChats: MessageNotificationSettings, groupChats: MessageNotificationSettings, channels: MessageNotificationSettings, reactionSettings: PeerReactionNotificationSettings, contactsJoined: Bool) {
self.privateChats = privateChats
self.groupChats = groupChats
self.channels = channels
self.reactionSettings = reactionSettings
self.contactsJoined = contactsJoined
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.privateChats = try container.decode(MessageNotificationSettings.self, forKey: "p")
self.groupChats = try container.decode(MessageNotificationSettings.self, forKey: "g")
self.channels = try container.decode(MessageNotificationSettings.self, forKey: "c")
self.reactionSettings = try container.decodeIfPresent(PeerReactionNotificationSettings.self, forKey: "reactionSettings") ?? PeerReactionNotificationSettings.default
self.contactsJoined = (try container.decode(Int32.self, forKey: "contactsJoined")) != 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.privateChats, forKey: "p")
try container.encode(self.groupChats, forKey: "g")
try container.encode(self.channels, forKey: "c")
try container.encode(self.reactionSettings, forKey: "reactionSettings")
try container.encode((self.contactsJoined ? 1 : 0) as Int32, forKey: "contactsJoined")
}
}
public struct GlobalNotificationSettings: Codable {
public var toBeSynchronized: GlobalNotificationSettingsSet?
public var remote: GlobalNotificationSettingsSet
public static var defaultSettings: GlobalNotificationSettings = GlobalNotificationSettings(toBeSynchronized: nil, remote: GlobalNotificationSettingsSet.defaultSettings)
public var effective: GlobalNotificationSettingsSet {
if let toBeSynchronized = self.toBeSynchronized {
return toBeSynchronized
} else {
return self.remote
}
}
public var postboxAccessor: PostboxGlobalNotificationSettings {
return PostboxGlobalNotificationSettings(
defaultIncludePeer: { peer in
return self.defaultIncludePeer(peer: peer)
}
)
}
func defaultIncludePeer(peer: Peer) -> Bool {
let settings = self.effective
if peer is TelegramUser || peer is TelegramSecretChat {
return settings.privateChats.enabled
} else if peer is TelegramGroup {
return settings.groupChats.enabled
} else if let channel = peer as? TelegramChannel {
switch channel.info {
case .group:
return settings.groupChats.enabled
case .broadcast:
return settings.channels.enabled
}
} else {
return false
}
}
/*public func isEqualInDefaultPeerInclusion(other: PostboxGlobalNotificationSettings) -> Bool {
guard let other = other as? GlobalNotificationSettings else {
return false
}
let settings = self.effective
let otherSettings = other.effective
if settings.privateChats.enabled != otherSettings.privateChats.enabled {
return false
}
if settings.groupChats.enabled != otherSettings.groupChats.enabled {
return false
}
if settings.channels.enabled != otherSettings.channels.enabled {
return false
}
return true
}*/
public init(toBeSynchronized: GlobalNotificationSettingsSet?, remote: GlobalNotificationSettingsSet) {
self.toBeSynchronized = toBeSynchronized
self.remote = remote
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.toBeSynchronized = try container.decodeIfPresent(GlobalNotificationSettingsSet.self, forKey: "s")
self.remote = try container.decode(GlobalNotificationSettingsSet.self, forKey: "r")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encodeIfPresent(self.toBeSynchronized, forKey: "s")
try container.encode(self.remote, forKey: "r")
}
}
@@ -0,0 +1,38 @@
import Postbox
public final class ImportableDeviceContactData: Equatable, PostboxCoding {
public let firstName: String
public let lastName: String
public let localIdentifiers: [String]
public init(firstName: String, lastName: String, localIdentifiers: [String]) {
self.firstName = firstName
self.lastName = lastName
self.localIdentifiers = localIdentifiers
}
public init(decoder: PostboxDecoder) {
self.firstName = decoder.decodeStringForKey("f", orElse: "")
self.lastName = decoder.decodeStringForKey("l", orElse: "")
self.localIdentifiers = decoder.decodeStringArrayForKey("dis")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.firstName, forKey: "f")
encoder.encodeString(self.lastName, forKey: "l")
encoder.encodeStringArray(self.localIdentifiers, forKey: "dis")
}
public static func ==(lhs: ImportableDeviceContactData, rhs: ImportableDeviceContactData) -> Bool {
if lhs.firstName != rhs.firstName {
return false
}
if lhs.lastName != rhs.lastName {
return false
}
if lhs.localIdentifiers != rhs.localIdentifiers {
return false
}
return true
}
}
@@ -0,0 +1,82 @@
import Foundation
import Postbox
public class InlineBotMessageAttribute: MessageAttribute {
public let peerId: PeerId?
public let title: String?
public var associatedPeerIds: [PeerId] {
if let peerId = self.peerId {
return [peerId]
} else {
return []
}
}
public init(peerId: PeerId?, title: String?) {
self.peerId = peerId
self.title = title
}
required public init(decoder: PostboxDecoder) {
if let peerId = decoder.decodeOptionalInt64ForKey("i") {
self.peerId = PeerId(peerId)
} else {
self.peerId = nil
}
self.title = decoder.decodeOptionalStringForKey("t")
}
public func encode(_ encoder: PostboxEncoder) {
if let peerId = self.peerId {
encoder.encodeInt64(peerId.toInt64(), forKey: "i")
} else {
encoder.encodeNil(forKey: "i")
}
if let title = self.title {
encoder.encodeString(title, forKey: "t")
} else {
encoder.encodeNil(forKey: "t")
}
}
}
public class InlineBusinessBotMessageAttribute: MessageAttribute {
public let peerId: PeerId?
public let title: String?
public var associatedPeerIds: [PeerId] {
if let peerId = self.peerId {
return [peerId]
} else {
return []
}
}
public init(peerId: PeerId?, title: String?) {
self.peerId = peerId
self.title = title
}
required public init(decoder: PostboxDecoder) {
if let peerId = decoder.decodeOptionalInt64ForKey("i") {
self.peerId = PeerId(peerId)
} else {
self.peerId = nil
}
self.title = decoder.decodeOptionalStringForKey("t")
}
public func encode(_ encoder: PostboxEncoder) {
if let peerId = self.peerId {
encoder.encodeInt64(peerId.toInt64(), forKey: "i")
} else {
encoder.encodeNil(forKey: "i")
}
if let title = self.title {
encoder.encodeString(title, forKey: "t")
} else {
encoder.encodeNil(forKey: "t")
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,123 @@
import Postbox
public indirect enum JSON: Codable, Equatable {
private struct DictionaryKey: Codable, Hashable {
var key: String
init(_ key: String) {
self.key = key
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.key = try container.decode(String.self, forKey: "k")
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.key, forKey: "k")
}
}
case null
case number(Double)
case string(String)
case bool(Bool)
case array([JSON])
case dictionary([String: JSON])
private enum ValueType: Int32 {
case null = 0
case number = 1
case string = 2
case bool = 3
case array = 4
case dictionary = 5
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
switch try container.decode(Int32.self, forKey: "r") {
case ValueType.null.rawValue:
self = .null
case ValueType.number.rawValue:
self = .number(try container.decode(Double.self, forKey: "v"))
case ValueType.string.rawValue:
self = .string(try container.decode(String.self, forKey: "v"))
case ValueType.bool.rawValue:
self = .bool(try container.decode(Bool.self, forKey: "v"))
case ValueType.array.rawValue:
self = .array(try container.decode([JSON].self, forKey: "v"))
case ValueType.dictionary.rawValue:
let dict = try container.decode([DictionaryKey: JSON].self, forKey: "v")
var mappedDict: [String: JSON] = [:]
for (key, value) in dict {
mappedDict[key.key] = value
}
self = .dictionary(mappedDict)
default:
self = .null
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self {
case .null:
try container.encode(ValueType.null.rawValue, forKey: "r")
case let .number(value):
try container.encode(ValueType.number.rawValue, forKey: "r")
try container.encode(value, forKey: "v")
case let .string(value):
try container.encode(ValueType.string.rawValue, forKey: "r")
try container.encode(value, forKey: "v")
case let .bool(value):
try container.encode(ValueType.bool.rawValue, forKey: "r")
try container.encode(value, forKey: "v")
case let .array(value):
try container.encode(ValueType.array.rawValue, forKey: "r")
try container.encode(value, forKey: "v")
case let .dictionary(value):
try container.encode(ValueType.dictionary.rawValue, forKey: "r")
var mappedDict: [DictionaryKey: JSON] = [:]
for (k, v) in value {
mappedDict[DictionaryKey(k)] = v
}
try container.encode(mappedDict, forKey: "v")
}
}
public enum Index: Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, JSON>)
case null
static public func ==(lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case let (.array(lhs), .array(rhs)):
return lhs == rhs
case let (.dictionary(lhs), .dictionary(rhs)):
return lhs == rhs
case (.null, .null):
return true
default:
return false
}
}
static public func <(lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case let (.array(lhs), .array(rhs)):
return lhs < rhs
case let (.dictionary(lhs), .dictionary(rhs)):
return lhs < rhs
default:
return false
}
}
}
}
@@ -0,0 +1,55 @@
import Postbox
public struct LimitsConfiguration: Codable, Equatable {
public static let timeIntervalForever: Int32 = 0x7fffffff
public var maxGroupMemberCount: Int32
public var maxSupergroupMemberCount: Int32
public var maxMessageForwardBatchSize: Int32
public var maxRecentStickerCount: Int32
public var maxMessageEditingInterval: Int32
public var canRemoveIncomingMessagesInPrivateChats: Bool
public var maxMessageRevokeInterval: Int32
public var maxMessageRevokeIntervalInPrivateChats: Int32
public static var defaultValue: LimitsConfiguration {
return LimitsConfiguration(maxGroupMemberCount: 200, maxSupergroupMemberCount: 200000, maxMessageForwardBatchSize: 50, maxRecentStickerCount: 20, maxMessageEditingInterval: 2 * 24 * 60 * 60, canRemoveIncomingMessagesInPrivateChats: false, maxMessageRevokeInterval: 2 * 24 * 60 * 60, maxMessageRevokeIntervalInPrivateChats: 2 * 24 * 60 * 60)
}
public init(maxGroupMemberCount: Int32, maxSupergroupMemberCount: Int32, maxMessageForwardBatchSize: Int32, maxRecentStickerCount: Int32, maxMessageEditingInterval: Int32, canRemoveIncomingMessagesInPrivateChats: Bool, maxMessageRevokeInterval: Int32, maxMessageRevokeIntervalInPrivateChats: Int32) {
self.maxGroupMemberCount = maxGroupMemberCount
self.maxSupergroupMemberCount = maxSupergroupMemberCount
self.maxMessageForwardBatchSize = maxMessageForwardBatchSize
self.maxRecentStickerCount = maxRecentStickerCount
self.maxMessageEditingInterval = maxMessageEditingInterval
self.canRemoveIncomingMessagesInPrivateChats = canRemoveIncomingMessagesInPrivateChats
self.maxMessageRevokeInterval = maxMessageRevokeInterval
self.maxMessageRevokeIntervalInPrivateChats = maxMessageRevokeIntervalInPrivateChats
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.maxGroupMemberCount = (try? container.decodeIfPresent(Int32.self, forKey: "maxGroupMemberCount")) ?? 200
self.maxSupergroupMemberCount = (try? container.decodeIfPresent(Int32.self, forKey: "maxSupergroupMemberCount")) ?? 5000
self.maxMessageForwardBatchSize = (try? container.decodeIfPresent(Int32.self, forKey: "maxMessageForwardBatchSize")) ?? 50
self.maxRecentStickerCount = (try? container.decodeIfPresent(Int32.self, forKey: "maxRecentStickerCount")) ?? 20
self.maxMessageEditingInterval = (try? container.decodeIfPresent(Int32.self, forKey: "maxMessageEditingInterval")) ?? (2 * 24 * 60 * 60)
self.canRemoveIncomingMessagesInPrivateChats = (try? container.decodeIfPresent(Int32.self, forKey: "canRemoveIncomingMessagesInPrivateChats") ?? 0) != 0
self.maxMessageRevokeInterval = (try? container.decodeIfPresent(Int32.self, forKey: "maxMessageRevokeInterval")) ?? (2 * 24 * 60 * 60)
self.maxMessageRevokeIntervalInPrivateChats = (try? container.decodeIfPresent(Int32.self, forKey: "maxMessageRevokeIntervalInPrivateChats")) ?? (2 * 24 * 60 * 60)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.maxGroupMemberCount, forKey: "maxGroupMemberCount")
try container.encode(self.maxSupergroupMemberCount, forKey: "maxSupergroupMemberCount")
try container.encode(self.maxMessageForwardBatchSize, forKey: "maxMessageForwardBatchSize")
try container.encode(self.maxRecentStickerCount, forKey: "maxRecentStickerCount")
try container.encode(self.maxMessageEditingInterval, forKey: "maxMessageEditingInterval")
try container.encode((self.canRemoveIncomingMessagesInPrivateChats ? 1 : 0) as Int32, forKey: "canRemoveIncomingMessagesInPrivateChats")
try container.encode(self.maxMessageRevokeInterval, forKey: "maxMessageRevokeInterval")
try container.encode(self.maxMessageRevokeIntervalInPrivateChats, forKey: "maxMessageRevokeIntervalInPrivateChats")
}
}
@@ -0,0 +1,44 @@
import Foundation
import Postbox
public struct LinksConfiguration: Equatable, Codable {
private enum CodingKeys: String, CodingKey {
case autologinToken
}
public let autologinToken: String?
public static var defaultValue: LinksConfiguration {
return LinksConfiguration(autologinToken: nil)
}
public init(autologinToken: String?) {
self.autologinToken = autologinToken
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.autologinToken = try container.decodeIfPresent(String.self, forKey: .autologinToken)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.autologinToken, forKey: .autologinToken)
}
}
public func currentLinksConfiguration(transaction: Transaction) -> LinksConfiguration {
if let entry = transaction.getPreferencesEntry(key: PreferencesKeys.linksConfiguration)?.get(LinksConfiguration.self) {
return entry
} else {
return LinksConfiguration.defaultValue
}
}
func updateLinksConfiguration(transaction: Transaction, configuration: LinksConfiguration) {
if currentLinksConfiguration(transaction: transaction) != configuration {
transaction.setPreferencesEntry(key: PreferencesKeys.linksConfiguration, value: PreferencesEntry(configuration))
}
}
@@ -0,0 +1,18 @@
import Foundation
import Postbox
public class LocalMediaPlaybackInfoAttribute: MessageAttribute {
public let data: Data
public init(data: Data) {
self.data = data
}
required public init(decoder: PostboxDecoder) {
self.data = decoder.decodeDataForKey("d") ?? Data()
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeData(self.data, forKey: "d")
}
}
@@ -0,0 +1,227 @@
import Foundation
import Postbox
public enum LocalizationEntry: Equatable {
case string(key: String, value: String)
case pluralizedString(key: String, zero: String?, one: String?, two: String?, few: String?, many: String?, other: String)
public var key: String {
switch self {
case let .string(key, _):
return key
case let .pluralizedString(key, _, _, _, _, _, _):
return key
}
}
}
private struct LocalizationEntryFlags: OptionSet {
var rawValue: Int8
init(rawValue: Int8) {
self.rawValue = rawValue
}
init() {
self.rawValue = 0
}
static let pluralized = LocalizationEntryFlags(rawValue: (1 << 0))
static let hasZero = LocalizationEntryFlags(rawValue: (1 << 1))
static let hasOne = LocalizationEntryFlags(rawValue: (1 << 2))
static let hasTwo = LocalizationEntryFlags(rawValue: (1 << 3))
static let hasFew = LocalizationEntryFlags(rawValue: (1 << 4))
static let hasMany = LocalizationEntryFlags(rawValue: (1 << 5))
}
private func writeString(_ buffer: WriteBuffer, _ string: String) {
if let data = string.data(using: .utf8) {
var length: Int32 = Int32(data.count)
buffer.write(&length, offset: 0, length: 4)
buffer.write(data)
} else {
var length: Int32 = 0
buffer.write(&length, offset: 0, length: 4)
}
}
public final class Localization: Codable, Equatable {
public let version: Int32
public let entries: [LocalizationEntry]
public init(version: Int32, entries: [LocalizationEntry]) {
self.version = version
self.entries = entries
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.version = (try? container.decode(Int32.self, forKey: "v")) ?? 0
let count = (try? container.decode(Int32.self, forKey: "c")) ?? 0
var entries: [LocalizationEntry] = []
if let rawData = try? container.decodeIfPresent(Data.self, forKey: "d") {
let data = ReadBuffer(data: rawData)
for _ in 0 ..< count {
var flagsValue: Int8 = 0
data.read(&flagsValue, offset: 0, length: 1)
let flags = LocalizationEntryFlags(rawValue: flagsValue)
var length: Int32 = 0
data.read(&length, offset: 0, length: 4)
let keyData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let key = String(data: keyData, encoding: .utf8)
data.skip(Int(length))
if flags.contains(.pluralized) {
var zero: String?
var one: String?
var two: String?
var few: String?
var many: String?
var other: String?
if flags.contains(.hasZero) {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
zero = value
}
if flags.contains(.hasOne) {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
one = value
}
if flags.contains(.hasTwo) {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
two = value
}
if flags.contains(.hasFew) {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
few = value
}
if flags.contains(.hasMany) {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
many = value
}
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
other = value
if let key = key, let other = other {
entries.append(.pluralizedString(key: key, zero: zero, one: one, two: two, few: few, many: many, other: other))
}
} else {
length = 0
data.read(&length, offset: 0, length: 4)
let valueData = Data(bytes: data.memory.advanced(by: data.offset), count: Int(length))
let value = String(data: valueData, encoding: .utf8)
data.skip(Int(length))
if let key = key, let value = value {
entries.append(.string(key: key, value: value))
}
}
}
}
self.entries = entries
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.version, forKey: "v")
try container.encode(Int32(self.entries.count), forKey: "c")
let buffer = WriteBuffer()
for entry in self.entries {
var flags: LocalizationEntryFlags = []
switch entry {
case .string:
flags = []
case let .pluralizedString(_, zero, one, two, few, many, _):
flags.insert(.pluralized)
if zero != nil {
flags.insert(.hasZero)
}
if one != nil {
flags.insert(.hasOne)
}
if two != nil {
flags.insert(.hasTwo)
}
if few != nil {
flags.insert(.hasFew)
}
if many != nil {
flags.insert(.hasMany)
}
}
var flagsValue: Int8 = flags.rawValue
buffer.write(&flagsValue, offset: 0, length: 1)
switch entry {
case let .string(key, value):
writeString(buffer, key)
writeString(buffer, value)
case let .pluralizedString(key, zero, one, two, few, many, other):
writeString(buffer, key)
if let zero = zero {
writeString(buffer, zero)
}
if let one = one {
writeString(buffer, one)
}
if let two = two {
writeString(buffer, two)
}
if let few = few {
writeString(buffer, few)
}
if let many = many {
writeString(buffer, many)
}
writeString(buffer, other)
}
}
try container.encode(buffer.makeData(), forKey: "d")
}
public static func ==(lhs: Localization, rhs: Localization) -> Bool {
if lhs === rhs {
return true
}
if lhs.entries == rhs.entries {
return true
}
return false
}
}
@@ -0,0 +1,85 @@
import Postbox
public struct LocalizationInfo: PostboxCoding, Codable, Equatable {
public let languageCode: String
public let baseLanguageCode: String?
public let customPluralizationCode: String?
public let title: String
public let localizedTitle: String
public let isOfficial: Bool
public let totalStringCount: Int32
public let translatedStringCount: Int32
public let platformUrl: String
public init(languageCode: String, baseLanguageCode: String?, customPluralizationCode: String?, title: String, localizedTitle: String, isOfficial: Bool, totalStringCount: Int32, translatedStringCount: Int32, platformUrl: String) {
self.languageCode = languageCode
self.baseLanguageCode = baseLanguageCode
self.customPluralizationCode = customPluralizationCode
self.title = title
self.localizedTitle = localizedTitle
self.isOfficial = isOfficial
self.totalStringCount = totalStringCount
self.translatedStringCount = translatedStringCount
self.platformUrl = platformUrl
}
public init(decoder: PostboxDecoder) {
self.languageCode = decoder.decodeStringForKey("lc", orElse: "")
self.baseLanguageCode = decoder.decodeOptionalStringForKey("nlc")
self.customPluralizationCode = decoder.decodeOptionalStringForKey("cpc")
self.title = decoder.decodeStringForKey("t", orElse: "")
self.localizedTitle = decoder.decodeStringForKey("lt", orElse: "")
self.isOfficial = decoder.decodeInt32ForKey("of", orElse: 0) != 0
self.totalStringCount = decoder.decodeInt32ForKey("tsc", orElse: 0)
self.translatedStringCount = decoder.decodeInt32ForKey("lsc", orElse: 0)
self.platformUrl = decoder.decodeStringForKey("platformUrl", orElse: "")
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.languageCode = (try? container.decode(String.self, forKey: "lc")) ?? ""
self.baseLanguageCode = try? container.decodeIfPresent(String.self, forKey: "nlc")
self.customPluralizationCode = try? container.decodeIfPresent(String.self, forKey: "cpc")
self.title = (try? container.decode(String.self, forKey: "t")) ?? ""
self.localizedTitle = (try? container.decode(String.self, forKey: "lt")) ?? ""
self.isOfficial = ((try? container.decode(Int32.self, forKey: "of")) ?? 0) != 0
self.totalStringCount = (try? container.decode(Int32.self, forKey: "tsc")) ?? 0
self.translatedStringCount = (try? container.decode(Int32.self, forKey: "lsc")) ?? 0
self.platformUrl = (try? container.decode(String.self, forKey: "platformUrl")) ?? ""
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.languageCode, forKey: "lc")
if let baseLanguageCode = self.baseLanguageCode {
encoder.encodeString(baseLanguageCode, forKey: "nlc")
} else {
encoder.encodeNil(forKey: "nlc")
}
if let customPluralizationCode = self.customPluralizationCode {
encoder.encodeString(customPluralizationCode, forKey: "cpc")
} else {
encoder.encodeNil(forKey: "cpc")
}
encoder.encodeString(self.title, forKey: "t")
encoder.encodeString(self.localizedTitle, forKey: "lt")
encoder.encodeInt32(self.isOfficial ? 1 : 0, forKey: "of")
encoder.encodeInt32(self.totalStringCount, forKey: "tsc")
encoder.encodeInt32(self.translatedStringCount, forKey: "lsc")
encoder.encodeString(self.platformUrl, forKey: "platformUrl")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.languageCode, forKey: "lc")
try container.encodeIfPresent(self.baseLanguageCode, forKey: "nlc")
try container.encodeIfPresent(self.customPluralizationCode, forKey: "cpc")
try container.encode(self.title, forKey: "t")
try container.encode(self.localizedTitle, forKey: "lt")
try container.encode((self.isOfficial ? 1 : 0) as Int32, forKey: "of")
try container.encode(self.totalStringCount, forKey: "tsc")
try container.encode(self.translatedStringCount, forKey: "lsc")
try container.encode(self.platformUrl, forKey: "platformUrl")
}
}
@@ -0,0 +1,29 @@
import Postbox
public struct LocalizationListState: Codable, Equatable {
public var availableOfficialLocalizations: [LocalizationInfo]
public var availableSavedLocalizations: [LocalizationInfo]
public static var defaultSettings: LocalizationListState {
return LocalizationListState(availableOfficialLocalizations: [], availableSavedLocalizations: [])
}
public init(availableOfficialLocalizations: [LocalizationInfo], availableSavedLocalizations: [LocalizationInfo]) {
self.availableOfficialLocalizations = availableOfficialLocalizations
self.availableSavedLocalizations = availableSavedLocalizations
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.availableOfficialLocalizations = (try? container.decode([LocalizationInfo].self, forKey: "availableOfficialLocalizations")) ?? []
self.availableSavedLocalizations = (try? container.decode([LocalizationInfo].self, forKey: "availableSavedLocalizations")) ?? []
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.availableOfficialLocalizations, forKey: "availableOfficialLocalizations")
try container.encode(self.availableSavedLocalizations, forKey: "availableSavedLocalizations")
}
}
@@ -0,0 +1,88 @@
import Foundation
import Postbox
public final class LocalizationComponent: Equatable, Codable {
public let languageCode: String
public let localizedName: String
public let localization: Localization
public let customPluralizationCode: String?
public init(languageCode: String, localizedName: String, localization: Localization, customPluralizationCode: String?) {
self.languageCode = languageCode
self.localizedName = localizedName
self.localization = localization
self.customPluralizationCode = customPluralizationCode
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.languageCode = (try? container.decode(String.self, forKey: "lc")) ?? ""
self.localizedName = (try? container.decode(String.self, forKey: "localizedName")) ?? ""
self.localization = try container.decode(Localization.self, forKey: "loc")
self.customPluralizationCode = try container.decodeIfPresent(String.self, forKey: "cpl")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.languageCode, forKey: "lc")
try container.encode(self.localizedName, forKey: "localizedName")
try container.encode(self.localization, forKey: "loc")
try container.encodeIfPresent(self.customPluralizationCode, forKey: "cpl")
}
public static func ==(lhs: LocalizationComponent, rhs: LocalizationComponent) -> Bool {
if lhs.languageCode != rhs.languageCode {
return false
}
if lhs.localizedName != rhs.localizedName {
return false
}
if lhs.localization != rhs.localization {
return false
}
if lhs.customPluralizationCode != rhs.customPluralizationCode {
return false
}
return true
}
}
public final class LocalizationSettings: Codable, Equatable {
public let primaryComponent: LocalizationComponent
public let secondaryComponent: LocalizationComponent?
public init(primaryComponent: LocalizationComponent, secondaryComponent: LocalizationComponent?) {
self.primaryComponent = primaryComponent
self.secondaryComponent = secondaryComponent
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let languageCode = try container.decodeIfPresent(String.self, forKey: "lc") {
self.primaryComponent = LocalizationComponent(
languageCode: languageCode,
localizedName: "",
localization: try container.decode(Localization.self, forKey: "loc"),
customPluralizationCode: nil
)
self.secondaryComponent = nil
} else {
self.primaryComponent = try container.decode(LocalizationComponent.self, forKey: "primaryComponent")
self.secondaryComponent = try container.decodeIfPresent(LocalizationComponent.self, forKey: "secondaryComponent")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.primaryComponent, forKey: "primaryComponent")
try container.encodeIfPresent(self.secondaryComponent, forKey: "secondaryComponent")
}
public static func ==(lhs: LocalizationSettings, rhs: LocalizationSettings) -> Bool {
return lhs.primaryComponent == rhs.primaryComponent && lhs.secondaryComponent == rhs.secondaryComponent
}
}
@@ -0,0 +1,17 @@
import Foundation
import Postbox
public final class LoggedOutAccountAttribute: Codable, Equatable {
public init() {
}
public init(from decoder: Decoder) throws {
}
public func encode(to encoder: Encoder) throws {
}
public static func ==(lhs: LoggedOutAccountAttribute, rhs: LoggedOutAccountAttribute) -> Bool {
return true
}
}
@@ -0,0 +1,60 @@
import Postbox
public final class LoggingSettings: Codable {
public let logToFile: Bool
public let logToConsole: Bool
public let redactSensitiveData: Bool
#if DEBUG
public static var defaultSettings = LoggingSettings(logToFile: false, logToConsole: false, redactSensitiveData: true)
#else
public static var defaultSettings = LoggingSettings(logToFile: false, logToConsole: false, redactSensitiveData: true)
#endif
public init(logToFile: Bool, logToConsole: Bool, redactSensitiveData: Bool) {
self.logToFile = logToFile
self.logToConsole = logToConsole
self.redactSensitiveData = redactSensitiveData
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.logToFile = ((try? container.decode(Int32.self, forKey: "logToFile")) ?? 0) != 0
self.logToConsole = ((try? container.decode(Int32.self, forKey: "logToConsole")) ?? 0) != 0
self.redactSensitiveData = ((try? container.decode(Int32.self, forKey: "redactSensitiveData")) ?? 1) != 0
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode((self.logToFile ? 1 : 0) as Int32, forKey: "logToFile")
try container.encode((self.logToConsole ? 1 : 0) as Int32, forKey: "logToConsole")
try container.encode((self.redactSensitiveData ? 1 : 0) as Int32, forKey: "redactSensitiveData")
}
public func withUpdatedLogToFile(_ logToFile: Bool) -> LoggingSettings {
return LoggingSettings(logToFile: logToFile, logToConsole: self.logToConsole, redactSensitiveData: self.redactSensitiveData)
}
public func withUpdatedLogToConsole(_ logToConsole: Bool) -> LoggingSettings {
return LoggingSettings(logToFile: self.logToFile, logToConsole: logToConsole, redactSensitiveData: self.redactSensitiveData)
}
public func withUpdatedRedactSensitiveData(_ redactSensitiveData: Bool) -> LoggingSettings {
return LoggingSettings(logToFile: self.logToFile, logToConsole: self.logToConsole, redactSensitiveData: redactSensitiveData)
}
public static func ==(lhs: LoggingSettings, rhs: LoggingSettings) -> Bool {
if lhs.logToFile != rhs.logToFile {
return false
}
if lhs.logToConsole != rhs.logToConsole {
return false
}
if lhs.redactSensitiveData != rhs.redactSensitiveData {
return false
}
return true
}
}
@@ -0,0 +1,972 @@
import Postbox
public struct MessageReference: PostboxCoding, Hashable, Equatable {
public let content: MessageReferenceContent
public var peer: PeerReference? {
switch content {
case .none:
return nil
case let .message(peer, _, _, _, _, _, _):
return peer
}
}
public var author: PeerReference? {
switch content {
case .none:
return nil
case let .message(_, author, _, _, _, _, _):
return author
}
}
public var id: MessageId? {
switch content {
case .none:
return nil
case let .message(_, _, id, _, _, _, _):
return id
}
}
public var timestamp: Int32? {
switch content {
case .none:
return nil
case let .message(_, _, _, timestamp, _, _, _):
return timestamp
}
}
public var isIncoming: Bool? {
switch content {
case .none:
return nil
case let .message(_, _, _, _, incoming, _, _):
return incoming
}
}
public var isSecret: Bool? {
switch content {
case .none:
return nil
case let .message(_, _, _, _, _, secret, _):
return secret
}
}
public var threadId: Int64? {
switch content {
case .none:
return nil
case let .message(_, _, _, _, _, _, threadId):
return threadId
}
}
init(content: MessageReferenceContent) {
self.content = content
}
public init(_ message: Message) {
if message.id.namespace != Namespaces.Message.Local, let peer = message.peers[message.id.peerId], let inputPeer = PeerReference(peer) {
let author: PeerReference?
if let peer = message.author {
author = PeerReference(peer)
} else {
author = nil
}
self.content = .message(peer: inputPeer, author: author, id: message.id, timestamp: message.timestamp, incoming: message.flags.contains(.Incoming), secret: message.containsSecretMedia, threadId: message.threadId)
} else {
self.content = .none
}
}
public init(peer: Peer, author: Peer?, id: MessageId, timestamp: Int32, incoming: Bool, secret: Bool, threadId: Int64?) {
if let inputPeer = PeerReference(peer) {
let a: PeerReference?
if let peer = author {
a = PeerReference(peer)
} else {
a = nil
}
self.content = .message(peer: inputPeer, author: a, id: id, timestamp: timestamp, incoming: incoming, secret: secret, threadId: threadId)
} else {
self.content = .none
}
}
public init(decoder: PostboxDecoder) {
self.content = decoder.decodeObjectForKey("c", decoder: { MessageReferenceContent(decoder: $0) }) as! MessageReferenceContent
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObject(self.content, forKey: "c")
}
}
public enum MessageReferenceContent: PostboxCoding, Hashable, Equatable {
case none
case message(peer: PeerReference, author: PeerReference?, id: MessageId, timestamp: Int32, incoming: Bool, secret: Bool, threadId: Int64?)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("_r", orElse: 0) {
case 0:
self = .none
case 1:
self = .message(peer: decoder.decodeObjectForKey("p", decoder: { PeerReference(decoder: $0) }) as! PeerReference, author: decoder.decodeObjectForKey("author") as? PeerReference, id: MessageId(peerId: PeerId(decoder.decodeInt64ForKey("i.p", orElse: 0)), namespace: decoder.decodeInt32ForKey("i.n", orElse: 0), id: decoder.decodeInt32ForKey("i.i", orElse: 0)), timestamp: 0, incoming: false, secret: false, threadId: decoder.decodeOptionalInt64ForKey("tid"))
default:
assertionFailure()
self = .none
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .none:
encoder.encodeInt32(0, forKey: "_r")
case let .message(peer, author, id, _, _, _, threadId):
encoder.encodeInt32(1, forKey: "_r")
encoder.encodeObject(peer, forKey: "p")
if let author = author {
encoder.encodeObject(author, forKey: "author")
} else {
encoder.encodeNil(forKey: "author")
}
encoder.encodeInt64(id.peerId.toInt64(), forKey: "i.p")
encoder.encodeInt32(id.namespace, forKey: "i.n")
encoder.encodeInt32(id.id, forKey: "i.i")
if let threadId {
encoder.encodeInt64(threadId, forKey: "tid")
} else {
encoder.encodeNil(forKey: "tid")
}
}
}
}
public struct WebpageReference: PostboxCoding, Hashable, Equatable {
public let content: WebpageReferenceContent
init(content: WebpageReferenceContent) {
self.content = content
}
public init(_ webPage: TelegramMediaWebpage) {
if case let .Loaded(content) = webPage.content {
self.content = .webPage(id: webPage.webpageId.id, url: content.url)
} else {
self.content = .none
}
}
public init(decoder: PostboxDecoder) {
self.content = decoder.decodeObjectForKey("c", decoder: { WebpageReferenceContent(decoder: $0) }) as! WebpageReferenceContent
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObject(self.content, forKey: "c")
}
}
public enum WebpageReferenceContent: PostboxCoding, Hashable, Equatable {
case none
case webPage(id: Int64, url: String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("_r", orElse: 0) {
case 0:
self = .none
case 1:
self = .webPage(id: decoder.decodeInt64ForKey("i", orElse: 0), url: decoder.decodeStringForKey("u", orElse: ""))
default:
assertionFailure()
self = .none
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .none:
encoder.encodeInt32(0, forKey: "_r")
case let .webPage(id, url):
encoder.encodeInt32(1, forKey: "_r")
encoder.encodeInt64(id, forKey: "i")
encoder.encodeString(url, forKey: "u")
}
}
}
public enum ThemeReference: PostboxCoding, Hashable, Equatable {
case slug(String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("r", orElse: 0) {
case 0:
self = .slug(decoder.decodeStringForKey("s", orElse: ""))
default:
self = .slug("")
assertionFailure()
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .slug(slug):
encoder.encodeInt32(0, forKey: "r")
encoder.encodeString(slug, forKey: "s")
}
}
public static func ==(lhs: ThemeReference, rhs: ThemeReference) -> Bool {
switch lhs {
case let .slug(slug):
if case .slug(slug) = rhs {
return true
} else {
return false
}
}
}
}
public enum WallpaperReference: PostboxCoding, Hashable, Equatable {
case slug(String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("r", orElse: 0) {
case 0:
self = .slug(decoder.decodeStringForKey("s", orElse: ""))
default:
self = .slug("")
assertionFailure()
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .slug(slug):
encoder.encodeInt32(0, forKey: "r")
encoder.encodeString(slug, forKey: "s")
}
}
public static func ==(lhs: WallpaperReference, rhs: WallpaperReference) -> Bool {
switch lhs {
case let .slug(slug):
if case .slug(slug) = rhs {
return true
} else {
return false
}
}
}
}
public enum AnyMediaReference: Equatable {
case standalone(media: Media)
case message(message: MessageReference, media: Media)
case webPage(webPage: WebpageReference, media: Media)
case stickerPack(stickerPack: StickerPackReference, media: Media)
case savedGif(media: Media)
case savedSticker(media: Media)
case recentSticker(media: Media)
case avatarList(peer: PeerReference, media: Media)
case attachBot(peer: PeerReference, media: Media)
case customEmoji(media: Media)
case story(peer: PeerReference, id: Int32, media: Media)
case starsTransaction(transaction: StarsTransactionReference, media: Media)
case savedMusic(peer: PeerReference, media: Media)
public static func ==(lhs: AnyMediaReference, rhs: AnyMediaReference) -> Bool {
switch lhs {
case let .standalone(lhsMedia):
if case let .standalone(rhsMedia) = rhs, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .message(lhsMessage, lhsMedia):
if case let .message(rhsMessage, rhsMedia) = rhs, lhsMessage == rhsMessage, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .webPage(lhsWebPage, lhsMedia):
if case let .webPage(rhsWebPage, rhsMedia) = rhs, lhsWebPage == rhsWebPage, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .stickerPack(lhsStickerPack, lhsMedia):
if case let .stickerPack(rhsStickerPack, rhsMedia) = rhs, lhsStickerPack == rhsStickerPack, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .savedGif(lhsMedia):
if case let .savedGif(rhsMedia) = rhs, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .savedSticker(lhsMedia):
if case let .savedSticker(rhsMedia) = rhs, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .recentSticker(lhsMedia):
if case let .recentSticker(rhsMedia) = rhs, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .avatarList(lhsPeer, lhsMedia):
if case let .avatarList(rhsPeer, rhsMedia) = rhs, lhsPeer == rhsPeer, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .attachBot(lhsPeer, lhsMedia):
if case let .attachBot(rhsPeer, rhsMedia) = rhs, lhsPeer == rhsPeer, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .customEmoji(lhsMedia):
if case let .customEmoji(rhsMedia) = rhs, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .story(lhsPeer, lhsId, lhsMedia):
if case let .story(rhsPeer, rhsId, rhsMedia) = rhs, lhsPeer == rhsPeer, lhsId == rhsId, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .starsTransaction(lhsTransaction, lhsMedia):
if case let .starsTransaction(rhsTransaction, rhsMedia) = rhs, lhsTransaction == rhsTransaction, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
case let .savedMusic(lhsPeer, lhsMedia):
if case let .savedMusic(rhsPeer, rhsMedia) = rhs, lhsPeer == rhsPeer, lhsMedia.isEqual(to: rhsMedia) {
return true
} else {
return false
}
}
}
public var partial: PartialMediaReference? {
switch self {
case .standalone:
return nil
case let .message(message, _):
return .message(message: message)
case let .webPage(webPage, _):
return .webPage(webPage: webPage)
case let .stickerPack(stickerPack, _):
return .stickerPack(stickerPack: stickerPack)
case .savedGif:
return .savedGif
case .savedSticker:
return .savedSticker
case .recentSticker:
return .recentSticker
case .avatarList:
return nil
case .attachBot:
return nil
case .customEmoji:
return nil
case .story:
return nil
case .starsTransaction:
return nil
case let .savedMusic(peer, _):
return .savedMusic(peer: peer)
}
}
public func concrete<T: Media>(_ type: T.Type) -> MediaReference<T>? {
switch self {
case let .standalone(media):
if let media = media as? T {
return .standalone(media: media)
}
case let .message(message, media):
if let media = media as? T {
return .message(message: message, media: media)
}
case let .webPage(webPage, media):
if let media = media as? T {
return .webPage(webPage: webPage, media: media)
}
case let .stickerPack(stickerPack, media):
if let media = media as? T {
return .stickerPack(stickerPack: stickerPack, media: media)
}
case let .savedGif(media):
if let media = media as? T {
return .savedGif(media: media)
}
case let .savedSticker(media):
if let media = media as? T {
return .savedSticker(media: media)
}
case let .recentSticker(media):
if let media = media as? T {
return .recentSticker(media: media)
}
case let .avatarList(peer, media):
if let media = media as? T {
return .avatarList(peer: peer, media: media)
}
case let .attachBot(peer, media):
if let media = media as? T {
return .attachBot(peer: peer, media: media)
}
case let .customEmoji(media):
if let media = media as? T {
return .customEmoji(media: media)
}
case let .story(peer, id, media):
if let media = media as? T {
return .story(peer: peer, id: id, media: media)
}
case let .starsTransaction(transaction, media):
if let media = media as? T {
return .starsTransaction(transaction: transaction, media: media)
}
case let .savedMusic(peer, media):
if let media = media as? T {
return .savedMusic(peer: peer, media: media)
}
}
return nil
}
public var media: Media {
switch self {
case let .standalone(media):
return media
case let .message(_, media):
return media
case let .webPage(_, media):
return media
case let .stickerPack(_, media):
return media
case let .savedGif(media):
return media
case let .savedSticker(media):
return media
case let .recentSticker(media):
return media
case let .avatarList(_, media):
return media
case let .attachBot(_, media):
return media
case let .customEmoji(media):
return media
case let .story(_, _, media):
return media
case let .starsTransaction(_, media):
return media
case let .savedMusic(_, media):
return media
}
}
public func withUpdatedMedia(_ media: Media) -> AnyMediaReference {
switch self {
case .standalone:
return .standalone(media: media)
case let .message(message, _):
return .message(message: message, media: media)
case let .webPage(webPage, _):
return .webPage(webPage: webPage, media: media)
case let .stickerPack(stickerPack, _):
return .stickerPack(stickerPack: stickerPack, media: media)
case .savedGif:
return .savedGif(media: media)
case .savedSticker:
return .savedSticker(media: media)
case .recentSticker:
return .recentSticker(media: media)
case let .avatarList(peer, _):
return .avatarList(peer: peer, media: media)
case let .attachBot(peer, _):
return .attachBot(peer: peer, media: media)
case .customEmoji:
return .customEmoji(media: media)
case let .story(peer, id, _):
return .story(peer: peer, id: id, media: media)
case let .starsTransaction(transaction, _):
return .starsTransaction(transaction: transaction, media: media)
case let .savedMusic(peer, _):
return .savedMusic(peer: peer, media: media)
}
}
public func resourceReference(_ resource: MediaResource) -> MediaResourceReference {
return .media(media: self, resource: resource)
}
}
public enum PartialMediaReference: Equatable {
private enum CodingCase: Int32 {
case message
case webPage
case stickerPack
case savedGif
case savedSticker
case recentSticker
case savedMusic
}
case message(message: MessageReference)
case webPage(webPage: WebpageReference)
case stickerPack(stickerPack: StickerPackReference)
case savedGif
case savedSticker
case recentSticker
case savedMusic(peer: PeerReference)
public init?(decoder: PostboxDecoder) {
guard let caseIdValue = decoder.decodeOptionalInt32ForKey("_r"), let caseId = CodingCase(rawValue: caseIdValue) else {
return nil
}
switch caseId {
case .message:
let message = decoder.decodeObjectForKey("msg", decoder: { MessageReference(decoder: $0) }) as! MessageReference
self = .message(message: message)
case .webPage:
let webPage = decoder.decodeObjectForKey("wpg", decoder: { WebpageReference(decoder: $0) }) as! WebpageReference
self = .webPage(webPage: webPage)
case .stickerPack:
let stickerPack = decoder.decodeObjectForKey("spk", decoder: { StickerPackReference(decoder: $0) }) as! StickerPackReference
self = .stickerPack(stickerPack: stickerPack)
case .savedGif:
self = .savedGif
case .savedSticker:
self = .savedSticker
case .recentSticker:
self = .recentSticker
case .savedMusic:
let peer = decoder.decodeObjectForKey("pg", decoder: { PeerReference(decoder: $0) }) as! PeerReference
self = .savedMusic(peer: peer)
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .message(message):
encoder.encodeInt32(CodingCase.message.rawValue, forKey: "_r")
encoder.encodeObject(message, forKey: "msg")
case let .webPage(webPage):
encoder.encodeInt32(CodingCase.webPage.rawValue, forKey: "_r")
encoder.encodeObject(webPage, forKey: "wpg")
case let .stickerPack(stickerPack):
encoder.encodeInt32(CodingCase.stickerPack.rawValue, forKey: "_r")
encoder.encodeObject(stickerPack, forKey: "spk")
case .savedGif:
encoder.encodeInt32(CodingCase.savedGif.rawValue, forKey: "_r")
case .savedSticker:
encoder.encodeInt32(CodingCase.savedSticker.rawValue, forKey: "_r")
case .recentSticker:
encoder.encodeInt32(CodingCase.recentSticker.rawValue, forKey: "_r")
case let .savedMusic(peer):
encoder.encodeInt32(CodingCase.savedMusic.rawValue, forKey: "_r")
encoder.encodeObject(peer, forKey: "pg")
}
}
public func mediaReference(_ media: Media) -> AnyMediaReference {
switch self {
case let .message(message):
return .message(message: message, media: media)
case let .webPage(webPage):
return .webPage(webPage: webPage, media: media)
case let .stickerPack(stickerPack):
return .stickerPack(stickerPack: stickerPack, media: media)
case .savedGif:
return .savedGif(media: media)
case .savedSticker:
return .savedSticker(media: media)
case .recentSticker:
return .recentSticker(media: media)
case let .savedMusic(peer):
return .savedMusic(peer: peer, media: media)
}
}
}
public enum MediaReference<T: Media> {
private enum CodingCase: Int32 {
case standalone
case message
case webPage
case stickerPack
case savedGif
case savedSticker
case recentSticker
case avatarList
case attachBot
case customEmoji
case story
case starsTransaction
case savedMusic
}
case standalone(media: T)
case message(message: MessageReference, media: T)
case webPage(webPage: WebpageReference, media: T)
case stickerPack(stickerPack: StickerPackReference, media: T)
case savedGif(media: T)
case savedSticker(media: T)
case recentSticker(media: T)
case avatarList(peer: PeerReference, media: T)
case attachBot(peer: PeerReference, media: T)
case customEmoji(media: T)
case story(peer: PeerReference, id: Int32, media: T)
case starsTransaction(transaction: StarsTransactionReference, media: T)
case savedMusic(peer: PeerReference, media: T)
public init?(decoder: PostboxDecoder) {
guard let caseIdValue = decoder.decodeOptionalInt32ForKey("_r"), let caseId = CodingCase(rawValue: caseIdValue) else {
return nil
}
switch caseId {
case .standalone:
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .standalone(media: media)
case .message:
let message = decoder.decodeObjectForKey("msg", decoder: { MessageReference(decoder: $0) }) as! MessageReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .message(message: message, media: media)
case .webPage:
let webPage = decoder.decodeObjectForKey("wpg", decoder: { WebpageReference(decoder: $0) }) as! WebpageReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .webPage(webPage: webPage, media: media)
case .stickerPack:
let stickerPack = decoder.decodeObjectForKey("spk", decoder: { StickerPackReference(decoder: $0) }) as! StickerPackReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .stickerPack(stickerPack: stickerPack, media: media)
case .savedGif:
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .savedGif(media: media)
case .savedSticker:
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .savedSticker(media: media)
case .recentSticker:
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .recentSticker(media: media)
case .avatarList:
let peer = decoder.decodeObjectForKey("pr", decoder: { PeerReference(decoder: $0) }) as! PeerReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .avatarList(peer: peer, media: media)
case .attachBot:
let peer = decoder.decodeObjectForKey("pr", decoder: { PeerReference(decoder: $0) }) as! PeerReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .attachBot(peer: peer, media: media)
case .customEmoji:
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .customEmoji(media: media)
case .story:
let peer = decoder.decodeObjectForKey("pr", decoder: { PeerReference(decoder: $0) }) as! PeerReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
let id = decoder.decodeInt32ForKey("sid", orElse: 0)
self = .story(peer: peer, id: id, media: media)
case .starsTransaction:
let transaction = decoder.decodeObjectForKey("tr", decoder: { StarsTransactionReference(decoder: $0) }) as! StarsTransactionReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .starsTransaction(transaction: transaction, media: media)
case .savedMusic:
let peer = decoder.decodeObjectForKey("pr", decoder: { PeerReference(decoder: $0) }) as! PeerReference
guard let media = decoder.decodeObjectForKey("m") as? T else {
return nil
}
self = .savedMusic(peer: peer, media: media)
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .standalone(media):
encoder.encodeInt32(CodingCase.standalone.rawValue, forKey: "_r")
encoder.encodeObject(media, forKey: "m")
case let .message(message, media):
encoder.encodeInt32(CodingCase.message.rawValue, forKey: "_r")
encoder.encodeObject(message, forKey: "msg")
encoder.encodeObject(media, forKey: "m")
case let .webPage(webPage, media):
encoder.encodeInt32(CodingCase.webPage.rawValue, forKey: "_r")
encoder.encodeObject(webPage, forKey: "wpg")
encoder.encodeObject(media, forKey: "m")
case let .stickerPack(stickerPack, media):
encoder.encodeInt32(CodingCase.stickerPack.rawValue, forKey: "_r")
encoder.encodeObject(stickerPack, forKey: "spk")
encoder.encodeObject(media, forKey: "m")
case let .savedGif(media):
encoder.encodeInt32(CodingCase.savedGif.rawValue, forKey: "_r")
encoder.encodeObject(media, forKey: "m")
case let .savedSticker(media):
encoder.encodeInt32(CodingCase.savedSticker.rawValue, forKey: "_r")
encoder.encodeObject(media, forKey: "m")
case let .recentSticker(media):
encoder.encodeInt32(CodingCase.recentSticker.rawValue, forKey: "_r")
encoder.encodeObject(media, forKey: "m")
case let .avatarList(peer, media):
encoder.encodeInt32(CodingCase.avatarList.rawValue, forKey: "_r")
encoder.encodeObject(peer, forKey: "pr")
encoder.encodeObject(media, forKey: "m")
case let .attachBot(peer, media):
encoder.encodeInt32(CodingCase.attachBot.rawValue, forKey: "_r")
encoder.encodeObject(peer, forKey: "pr")
encoder.encodeObject(media, forKey: "m")
case let .customEmoji(media):
encoder.encodeInt32(CodingCase.customEmoji.rawValue, forKey: "_r")
encoder.encodeObject(media, forKey: "m")
case let .story(peer, id, media):
encoder.encodeInt32(CodingCase.story.rawValue, forKey: "_r")
encoder.encodeObject(peer, forKey: "pr")
encoder.encodeInt32(id, forKey: "sid")
encoder.encodeObject(media, forKey: "m")
case let .starsTransaction(transaction, media):
encoder.encodeInt32(CodingCase.starsTransaction.rawValue, forKey: "_r")
encoder.encodeObject(transaction, forKey: "tr")
encoder.encodeObject(media, forKey: "m")
case let .savedMusic(peer, media):
encoder.encodeInt32(CodingCase.savedMusic.rawValue, forKey: "_r")
encoder.encodeObject(peer, forKey: "pr")
encoder.encodeObject(media, forKey: "m")
}
}
public var abstract: AnyMediaReference {
switch self {
case let .standalone(media):
return .standalone(media: media)
case let .message(message, media):
return .message(message: message, media: media)
case let .webPage(webPage, media):
return .webPage(webPage: webPage, media: media)
case let .stickerPack(stickerPack, media):
return .stickerPack(stickerPack: stickerPack, media: media)
case let .savedGif(media):
return .savedGif(media: media)
case let .savedSticker(media):
return .savedSticker(media: media)
case let .recentSticker(media):
return .recentSticker(media: media)
case let .avatarList(peer, media):
return .avatarList(peer: peer, media: media)
case let .attachBot(peer, media):
return .attachBot(peer: peer, media: media)
case let .customEmoji(media):
return .customEmoji(media: media)
case let .story(peer, id, media):
return .story(peer: peer, id: id, media: media)
case let .starsTransaction(transaction, media):
return .starsTransaction(transaction: transaction, media: media)
case let .savedMusic(peer, media):
return .savedMusic(peer: peer, media: media)
}
}
public var partial: PartialMediaReference? {
return self.abstract.partial
}
public var media: T {
switch self {
case let .standalone(media):
return media
case let .message(_, media):
return media
case let .webPage(_, media):
return media
case let .stickerPack(_, media):
return media
case let .savedGif(media):
return media
case let .savedSticker(media):
return media
case let .recentSticker(media):
return media
case let .avatarList(_, media):
return media
case let .attachBot(_, media):
return media
case let .customEmoji(media):
return media
case let .story(_, _, media):
return media
case let .starsTransaction(_, media):
return media
case let .savedMusic(_, media):
return media
}
}
public func withMedia(_ media: T) -> MediaReference<T> {
switch self {
case .standalone:
return .standalone(media: media)
case let .message(message, _):
return .message(message: message, media: media)
case let .webPage(webPage, _):
return .webPage(webPage: webPage, media: media)
case let .stickerPack(stickerPack, _):
return .stickerPack(stickerPack: stickerPack, media: media)
case .savedGif:
return .savedGif(media: media)
case .savedSticker:
return .savedSticker(media: media)
case .recentSticker:
return .recentSticker(media: media)
case let .avatarList(peer, _):
return .avatarList(peer: peer, media: media)
case let .attachBot(peer, _):
return .attachBot(peer: peer, media: media)
case .customEmoji:
return .customEmoji(media: media)
case let .story(peer, id, _):
return .story(peer: peer, id: id, media: media)
case let .starsTransaction(transaction, _):
return .starsTransaction(transaction: transaction, media: media)
case let .savedMusic(peer, _):
return .savedMusic(peer: peer, media: media)
}
}
public func resourceReference(_ resource: MediaResource) -> MediaResourceReference {
return .media(media: self.abstract, resource: resource)
}
}
public typealias FileMediaReference = MediaReference<TelegramMediaFile>
public typealias ImageMediaReference = MediaReference<TelegramMediaImage>
public enum MediaResourceReference: Equatable {
case media(media: AnyMediaReference, resource: MediaResource)
case standalone(resource: MediaResource)
case avatar(peer: PeerReference, resource: MediaResource)
case avatarList(peer: PeerReference, resource: MediaResource)
case messageAuthorAvatar(message: MessageReference, resource: MediaResource)
case wallpaper(wallpaper: WallpaperReference?, resource: MediaResource)
case stickerPackThumbnail(stickerPack: StickerPackReference, resource: MediaResource)
case theme(theme: ThemeReference, resource: MediaResource)
case soundList(resource: MediaResource)
public var resource: MediaResource {
switch self {
case let .media(_, resource):
return resource
case let .standalone(resource):
return resource
case let .avatar(_, resource):
return resource
case let .avatarList(_, resource):
return resource
case let .messageAuthorAvatar(_, resource):
return resource
case let .wallpaper(_, resource):
return resource
case let .stickerPackThumbnail(_, resource):
return resource
case let .theme(_, resource):
return resource
case let .soundList(resource):
return resource
}
}
public static func ==(lhs: MediaResourceReference, rhs: MediaResourceReference) -> Bool {
switch lhs {
case let .media(lhsMedia, lhsResource):
if case let .media(rhsMedia, rhsResource) = rhs, lhsMedia == rhsMedia, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .standalone(lhsResource):
if case let .standalone(rhsResource) = rhs, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .avatar(lhsPeer, lhsResource):
if case let .avatar(rhsPeer, rhsResource) = rhs, lhsPeer == rhsPeer, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .avatarList(lhsPeer, lhsResource):
if case let .avatarList(rhsPeer, rhsResource) = rhs, lhsPeer == rhsPeer, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .messageAuthorAvatar(lhsMessage, lhsResource):
if case let .messageAuthorAvatar(rhsMessage, rhsResource) = rhs, lhsMessage == rhsMessage, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .wallpaper(lhsWallpaper, lhsResource):
if case let .wallpaper(rhsWallpaper, rhsResource) = rhs, lhsWallpaper == rhsWallpaper, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .stickerPackThumbnail(lhsStickerPack, lhsResource):
if case let .stickerPackThumbnail(rhsStickerPack, rhsResource) = rhs, lhsStickerPack == rhsStickerPack, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .theme(lhsTheme, lhsResource):
if case let .theme(rhsTheme, rhsResource) = rhs, lhsTheme == rhsTheme, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
case let .soundList(lhsResource):
if case let .soundList(rhsResource) = rhs, lhsResource.isEqual(to: rhsResource) {
return true
} else {
return false
}
}
}
}
@@ -0,0 +1,171 @@
import Postbox
import FlatBuffers
import FlatSerialization
public extension PeerId {
init(flatBuffersObject: TelegramCore_PeerId) {
self.init(namespace: PeerId.Namespace._internalFromInt32Value(flatBuffersObject.namespace), id: PeerId.Id._internalFromInt64Value(flatBuffersObject.id))
}
}
public extension MessageId {
init(flatBuffersObject: TelegramCore_MessageId) {
self.init(peerId: PeerId(flatBuffersObject: flatBuffersObject.peerId), namespace: flatBuffersObject.namespace, id: flatBuffersObject.id)
}
}
public extension MessageReference {
init(flatBuffersObject: TelegramCore_MessageReference) throws {
self.init(content: .message(
peer: try PeerReference(flatBuffersObject: flatBuffersObject.peer),
author: try flatBuffersObject.author.flatMap { try PeerReference(flatBuffersObject: $0) },
id: MessageId(flatBuffersObject: flatBuffersObject.messageId),
timestamp: flatBuffersObject.timestamp,
incoming: flatBuffersObject.incoming,
secret: flatBuffersObject.secret,
threadId: flatBuffersObject.threadId == Int64.min ? nil : flatBuffersObject.threadId)
)
}
func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset? {
switch self.content {
case let .message(peer, author, id, timestamp, incoming, secret, threadId):
let peerOffset = peer.encodeToFlatBuffers(builder: &builder)
let authorOffset = author.flatMap { $0.encodeToFlatBuffers(builder: &builder) }
let start = TelegramCore_MessageReference.startMessageReference(&builder)
TelegramCore_MessageReference.add(peer: peerOffset, &builder)
if let authorOffset {
TelegramCore_MessageReference.add(author: authorOffset, &builder)
}
TelegramCore_MessageReference.add(messageId: TelegramCore_MessageId(peerId: TelegramCore_PeerId(namespace: id.peerId.namespace._internalGetInt32Value(), id: id.peerId.id._internalGetInt64Value()), namespace: id.namespace, id: id.id), &builder)
TelegramCore_MessageReference.add(timestamp: timestamp, &builder)
TelegramCore_MessageReference.add(incoming: incoming, &builder)
TelegramCore_MessageReference.add(secret: secret, &builder)
TelegramCore_MessageReference.add(threadId: threadId ?? Int64.min, &builder)
return TelegramCore_MessageReference.endMessageReference(&builder, start: start)
case .none:
return nil
}
}
}
public extension WebpageReference {
init(flatBuffersObject: TelegramCore_WebpageReference) throws {
self.init(content: .webPage(id: flatBuffersObject.webpageId, url: flatBuffersObject.url))
}
func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset? {
switch self.content {
case let .webPage(id, url):
let urlOffset = builder.create(string: url)
let start = TelegramCore_WebpageReference.startWebpageReference(&builder)
TelegramCore_WebpageReference.add(webpageId: id, &builder)
TelegramCore_WebpageReference.add(url: urlOffset, &builder)
return TelegramCore_WebpageReference.endWebpageReference(&builder, start: start)
case .none:
return nil
}
}
}
public extension PartialMediaReference {
init?(flatBuffersObject: TelegramCore_PartialMediaReference) throws {
switch flatBuffersObject.valueType {
case .partialmediareferenceMessage:
guard let value = flatBuffersObject.value(type: TelegramCore_PartialMediaReference_Message.self) else {
throw FlatBuffersError.missingRequiredField()
}
if let message = value.message {
self = .message(message: try MessageReference(flatBuffersObject: message))
} else {
self = .message(message: MessageReference(content: .none))
}
case .partialmediareferenceWebpage:
guard let value = flatBuffersObject.value(type: TelegramCore_PartialMediaReference_WebPage.self) else {
throw FlatBuffersError.missingRequiredField()
}
if let webPage = value.webPage {
self = .webPage(webPage: try WebpageReference(flatBuffersObject: webPage))
} else {
self = .webPage(webPage: WebpageReference(content: .none))
}
case .partialmediareferenceStickerpack:
guard let value = flatBuffersObject.value(type: TelegramCore_PartialMediaReference_StickerPack.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .stickerPack(stickerPack: try StickerPackReference(flatBuffersObject: value.stickerPack))
case .partialmediareferenceSavedgif:
self = .savedGif
case .partialmediareferenceSavedsticker:
self = .savedSticker
case .partialmediareferenceRecentsticker:
self = .recentSticker
case .partialmediareferenceSavedmusic:
guard let value = flatBuffersObject.value(type: TelegramCore_PartialMediaReference_SavedMusic.self) else {
throw FlatBuffersError.missingRequiredField()
}
if let peer = value.peer {
self = .savedMusic(peer: try PeerReference(flatBuffersObject: peer))
} else {
return nil
}
case .none_:
throw FlatBuffersError.missingRequiredField()
}
}
func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset {
let valueType: TelegramCore_PartialMediaReference_Value
let valueOffset: Offset
switch self {
case let .message(message):
let messageOffset = message.encodeToFlatBuffers(builder: &builder)
let start = TelegramCore_PartialMediaReference_Message.startPartialMediaReference_Message(&builder)
if let messageOffset {
TelegramCore_PartialMediaReference_Message.add(message: messageOffset, &builder)
}
valueType = .partialmediareferenceMessage
valueOffset = TelegramCore_PartialMediaReference_Message.endPartialMediaReference_Message(&builder, start: start)
case let .webPage(webPage):
let webpageOffset = webPage.encodeToFlatBuffers(builder: &builder)
let start = TelegramCore_PartialMediaReference_WebPage.startPartialMediaReference_WebPage(&builder)
if let webpageOffset {
TelegramCore_PartialMediaReference_WebPage.add(webPage: webpageOffset, &builder)
}
valueType = .partialmediareferenceWebpage
valueOffset = TelegramCore_PartialMediaReference_WebPage.endPartialMediaReference_WebPage(&builder, start: start)
case let .stickerPack(stickerPack):
let stickerPackOffset = stickerPack.encodeToFlatBuffers(builder: &builder)
let start = TelegramCore_PartialMediaReference_StickerPack.startPartialMediaReference_StickerPack(&builder)
TelegramCore_PartialMediaReference_StickerPack.add(stickerPack: stickerPackOffset, &builder)
valueType = .partialmediareferenceStickerpack
valueOffset = TelegramCore_PartialMediaReference_StickerPack.endPartialMediaReference_StickerPack(&builder, start: start)
case .savedGif:
let start = TelegramCore_PartialMediaReference_SavedGif.startPartialMediaReference_SavedGif(&builder)
valueType = .partialmediareferenceSavedgif
valueOffset = TelegramCore_PartialMediaReference_SavedGif.endPartialMediaReference_SavedGif(&builder, start: start)
case .savedSticker:
let start = TelegramCore_PartialMediaReference_SavedSticker.startPartialMediaReference_SavedSticker(&builder)
valueType = .partialmediareferenceSavedsticker
valueOffset = TelegramCore_PartialMediaReference_SavedSticker.endPartialMediaReference_SavedSticker(&builder, start: start)
case .recentSticker:
let start = TelegramCore_PartialMediaReference_RecentSticker.startPartialMediaReference_RecentSticker(&builder)
valueType = .partialmediareferenceRecentsticker
valueOffset = TelegramCore_PartialMediaReference_RecentSticker.endPartialMediaReference_RecentSticker(&builder, start: start)
case let .savedMusic(peer):
let peerOffset = peer.encodeToFlatBuffers(builder: &builder)
let start = TelegramCore_PartialMediaReference_SavedMusic.startPartialMediaReference_SavedMusic(&builder)
TelegramCore_PartialMediaReference_SavedMusic.add(peer: peerOffset, &builder)
valueType = .partialmediareferenceSavedmusic
valueOffset = TelegramCore_PartialMediaReference_SavedMusic.endPartialMediaReference_SavedMusic(&builder, start: start)
}
return TelegramCore_PartialMediaReference.createPartialMediaReference(&builder, valueType: valueType, valueOffset: valueOffset)
}
}
@@ -0,0 +1,16 @@
import Foundation
import Postbox
public class MediaSpoilerMessageAttribute: MessageAttribute {
public var associatedMessageIds: [MessageId] = []
public init() {
}
required public init(decoder: PostboxDecoder) {
}
public func encode(_ encoder: PostboxEncoder) {
}
}
@@ -0,0 +1,677 @@
import Foundation
import Postbox
public struct Namespaces {
public struct Message {
public static let Cloud: Int32 = 0
public static let Local: Int32 = 1
public static let SecretIncoming: Int32 = 2
public static let ScheduledCloud: Int32 = 3
public static let ScheduledLocal: Int32 = 4
public static let QuickReplyCloud: Int32 = 5
public static let QuickReplyLocal: Int32 = 6
public static let allScheduled: Set<Int32> = Set([Namespaces.Message.ScheduledCloud, Namespaces.Message.ScheduledLocal])
public static let allQuickReply: Set<Int32> = Set([Namespaces.Message.QuickReplyCloud, Namespaces.Message.QuickReplyLocal])
public static let allNonRegular: Set<Int32> = Set([Namespaces.Message.ScheduledCloud, Namespaces.Message.ScheduledLocal, Namespaces.Message.QuickReplyCloud, Namespaces.Message.QuickReplyLocal])
public static let allLocal: [Int32] = [
Namespaces.Message.Local,
Namespaces.Message.SecretIncoming,
Namespaces.Message.ScheduledLocal,
Namespaces.Message.QuickReplyLocal
]
}
public struct Media {
public static let CloudImage: Int32 = 0
public static let CloudAudio: Int32 = 2
public static let CloudContact: Int32 = 3
public static let CloudMap: Int32 = 4
public static let CloudFile: Int32 = 5
public static let CloudWebpage: Int32 = 6
public static let LocalImage: Int32 = 7
public static let LocalFile: Int32 = 8
public static let CloudSecretImage: Int32 = 9
public static let CloudSecretFile: Int32 = 10
public static let CloudGame: Int32 = 11
public static let CloudInvoice: Int32 = 12
public static let LocalWebpage: Int32 = 13
public static let LocalPoll: Int32 = 14
public static let CloudPoll: Int32 = 15
}
public struct Peer {
public static let CloudUser = PeerId.Namespace._internalFromInt32Value(0)
public static let CloudGroup = PeerId.Namespace._internalFromInt32Value(1)
public static let CloudChannel = PeerId.Namespace._internalFromInt32Value(2)
public static let SecretChat = PeerId.Namespace._internalFromInt32Value(3)
public static let Empty = PeerId.Namespace.max
}
public struct ItemCollection {
public static let CloudStickerPacks: Int32 = 0
public static let CloudMaskPacks: Int32 = 1
public static let EmojiKeywords: Int32 = 2
public static let CloudAnimatedEmoji: Int32 = 3
public static let CloudDice: Int32 = 4
public static let CloudAnimatedEmojiAnimations: Int32 = 5
public static let CloudAnimatedEmojiReactions: Int32 = 6
public static let CloudPremiumGifts: Int32 = 7
public static let CloudEmojiPacks: Int32 = 8
public static let CloudEmojiGenericAnimations: Int32 = 9
public static let CloudIconStatusEmoji: Int32 = 10
public static let CloudIconTopicEmoji: Int32 = 11
public static let CloudIconChannelStatusEmoji: Int32 = 12
public static let CloudTonGifts: Int32 = 13
}
public struct OrderedItemList {
public static let CloudRecentStickers: Int32 = 0
public static let CloudRecentGifs: Int32 = 1
public static let RecentlySearchedPeerIds: Int32 = 2
public static let CloudRecentInlineBots: Int32 = 3
public static let CloudFeaturedStickerPacks: Int32 = 4
public static let CloudArchivedStickerPacks: Int32 = 5
public static let CloudWallpapers: Int32 = 6
public static let CloudSavedStickers: Int32 = 7
public static let RecentlyUsedHashtags: Int32 = 8
public static let CloudThemes: Int32 = 9
public static let CloudGreetingStickers: Int32 = 10
public static let RecentDownloads: Int32 = 11
public static let PremiumStickers: Int32 = 12
public static let CloudPremiumStickers: Int32 = 13
public static let LocalRecentEmoji: Int32 = 14
public static let CloudFeaturedEmojiPacks: Int32 = 15
public static let CloudAllPremiumStickers: Int32 = 16
public static let CloudRecentStatusEmoji: Int32 = 17
public static let CloudFeaturedStatusEmoji: Int32 = 18
public static let CloudRecentReactions: Int32 = 19
public static let CloudTopReactions: Int32 = 20
public static let CloudEmojiCategories: Int32 = 21
public static let CloudEmojiStatusCategories: Int32 = 22
public static let CloudFeaturedProfilePhotoEmoji: Int32 = 23
public static let CloudFeaturedGroupPhotoEmoji: Int32 = 24
public static let NewSessionReviews: Int32 = 25
public static let CloudFeaturedBackgroundIconEmoji: Int32 = 26
public static let CloudFeaturedChannelStatusEmoji: Int32 = 27
public static let CloudDisabledChannelStatusEmoji: Int32 = 28
public static let CloudDefaultTagReactions: Int32 = 29
public static let CloudUniqueStarGifts: Int32 = 30
}
public struct CachedItemCollection {
public static let resolvedByNamePeers: Int8 = 0
public static let cachedTwoStepToken: Int8 = 1
public static let cachedStickerPacks: Int8 = 2
public static let cachedAvailableLocalizations: Int8 = 3
public static let cachedSentMediaReferences: Int8 = 4
public static let cachedStickerQueryResults: Int8 = 5
public static let cachedSecureIdConfiguration: Int8 = 6
public static let cachedWallpapersConfiguration: Int8 = 7
public static let cachedThemesConfiguration: Int8 = 8
public static let cachedPollResults: Int8 = 9
public static let cachedContextResults: Int8 = 10
public static let proximityNotificationStoredState: Int8 = 11
public static let cachedGroupCallDisplayAsPeers: Int8 = 14
public static let cachedAdMessageStates: Int8 = 15
public static let cachedPeerInvitationImporters: Int8 = 16
public static let cachedPeerExportedInvitations: Int8 = 17
public static let cachedSendAsPeers: Int8 = 18
public static let availableReactions: Int8 = 19
public static let resolvedByPhonePeers: Int8 = 20
public static let notificationSoundList: Int8 = 22
public static let attachMenuBots: Int8 = 23
public static let featuredStickersConfiguration: Int8 = 24
public static let emojiSearchCategories: Int8 = 25
public static let cachedEmojiQueryResults: Int8 = 26
public static let cachedPeerStoryListHeads: Int8 = 27
public static let displayedStoryNotifications: Int8 = 28
public static let storySendAsPeerIds: Int8 = 29
public static let cachedChannelBoosts: Int8 = 31
public static let displayedMessageNotifications: Int8 = 32
public static let recommendedChannels: Int8 = 33
public static let peerColorOptions: Int8 = 34
public static let savedMessageTags: Int8 = 35
public static let applicationIcons: Int8 = 36
public static let availableMessageEffects: Int8 = 37
public static let cachedStarsRevenueStats: Int8 = 38
public static let cachedRevenueStats: Int8 = 39
public static let recommendedApps: Int8 = 40
public static let starsReactionDefaultToPrivate: Int8 = 41
public static let cachedPremiumGiftCodeOptions: Int8 = 42
public static let cachedProfileGifts: Int8 = 43
public static let recommendedBots: Int8 = 44
public static let channelsForPublicReaction: Int8 = 45
public static let cachedGroupsInCommon: Int8 = 46
public static let groupCallPersistentSettings: Int8 = 47
public static let cachedProfileGiftsCollections: Int8 = 48
public static let cachedProfileSavedMusic: Int8 = 49
public static let cachedChatThemes: Int8 = 50
public static let cachedLiveStorySendAsPeers: Int8 = 51
public static let cachedGiftUpgradesAttributes: Int8 = 52
}
public struct UnorderedItemList {
public static let synchronizedDeviceContacts: UnorderedItemListEntryTag = {
let key = ValueBoxKey(length: 1)
key.setUInt8(0, value: 0)
return UnorderedItemListEntryTag(value: key)
}()
}
public struct PeerGroup {
public static let archive = PeerGroupId(rawValue: 1)
}
}
public extension MessageTags {
static let photoOrVideo = MessageTags(rawValue: 1 << 0)
static let file = MessageTags(rawValue: 1 << 1)
static let music = MessageTags(rawValue: 1 << 2)
static let webPage = MessageTags(rawValue: 1 << 3)
static let voiceOrInstantVideo = MessageTags(rawValue: 1 << 4)
static let unseenPersonalMessage = MessageTags(rawValue: 1 << 5)
static let liveLocation = MessageTags(rawValue: 1 << 6)
static let gif = MessageTags(rawValue: 1 << 7)
static let photo = MessageTags(rawValue: 1 << 8)
static let video = MessageTags(rawValue: 1 << 9)
static let pinned = MessageTags(rawValue: 1 << 10)
static let unseenReaction = MessageTags(rawValue: 1 << 11)
static let voice = MessageTags(rawValue: 1 << 12)
static let roundVideo = MessageTags(rawValue: 1 << 13)
static let all: MessageTags = [.photoOrVideo, .file, .music, .webPage, .voiceOrInstantVideo, .unseenPersonalMessage, .liveLocation, .gif, .photo, .video, .pinned, .unseenReaction, .voice, .roundVideo]
}
public extension GlobalMessageTags {
static let Calls = GlobalMessageTags(rawValue: 1 << 0)
static let MissedCalls = GlobalMessageTags(rawValue: 1 << 1)
static let all: GlobalMessageTags = [.Calls, .MissedCalls]
}
public extension LocalMessageTags {
static let OutgoingLiveLocation = LocalMessageTags(rawValue: 1 << 0)
static let OutgoingDeliveredToServer = LocalMessageTags(rawValue: 1 << 1)
}
public extension PendingMessageActionType {
static let consumeUnseenPersonalMessage = PendingMessageActionType(rawValue: 0)
static let updateReaction = PendingMessageActionType(rawValue: 1)
static let sendScheduledMessageImmediately = PendingMessageActionType(rawValue: 2)
static let readReaction = PendingMessageActionType(rawValue: 3)
static let sendStarsReaction = PendingMessageActionType(rawValue: 4)
static let sendPostponedPaidMessage = PendingMessageActionType(rawValue: 5)
}
public let peerIdNamespacesWithInitialCloudMessageHoles = [Namespaces.Peer.CloudUser, Namespaces.Peer.CloudGroup, Namespaces.Peer.CloudChannel]
public struct OperationLogTags {
public static let SecretOutgoing = PeerOperationLogTag(value: 0)
public static let SecretIncomingEncrypted = PeerOperationLogTag(value: 1)
public static let SecretIncomingDecrypted = PeerOperationLogTag(value: 2)
public static let CloudChatRemoveMessages = PeerOperationLogTag(value: 3)
public static let SynchronizePinnedCloudChats = PeerOperationLogTag(value: 4)
public static let AutoremoveMessages = PeerOperationLogTag(value: 5)
public static let SynchronizePinnedChats = PeerOperationLogTag(value: 6)
public static let SynchronizeConsumeMessageContents = PeerOperationLogTag(value: 7)
public static let SynchronizeInstalledStickerPacks = PeerOperationLogTag(value: 8)
public static let SynchronizeInstalledMasks = PeerOperationLogTag(value: 9)
public static let SynchronizeMarkFeaturedStickerPacksAsSeen = PeerOperationLogTag(value: 10)
public static let SynchronizeChatInputStates = PeerOperationLogTag(value: 11)
public static let SynchronizeSavedGifs = PeerOperationLogTag(value: 12)
public static let SynchronizeLocalizationUpdates = PeerOperationLogTag(value: 13)
public static let SynchronizeSavedStickers = PeerOperationLogTag(value: 14)
public static let SynchronizeGroupedPeers = PeerOperationLogTag(value: 15)
public static let SynchronizeMarkAllUnseenPersonalMessages = PeerOperationLogTag(value: 16)
public static let SynchronizeRecentlyUsedStickers = PeerOperationLogTag(value: 17)
public static let SynchronizeAppLogEvents = PeerOperationLogTag(value: 18)
public static let SynchronizeEmojiKeywords = PeerOperationLogTag(value: 19)
public static let SynchronizeChatListFilters = PeerOperationLogTag(value: 20)
public static let SynchronizeMarkAllUnseenReactions = PeerOperationLogTag(value: 21)
public static let SynchronizeInstalledEmoji = PeerOperationLogTag(value: 22)
public static let SynchronizeAutosaveItems = PeerOperationLogTag(value: 23)
public static let SynchronizeViewStories = PeerOperationLogTag(value: 24)
public static let SynchronizePeerStories = PeerOperationLogTag(value: 25)
public static let SynchronizePinnedSavedChats = PeerOperationLogTag(value: 26)
}
public struct LegacyPeerSummaryCounterTags: OptionSet, Sequence, Hashable {
public var rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let regularChatsAndPrivateGroups = LegacyPeerSummaryCounterTags(rawValue: 1 << 0)
public static let publicGroups = LegacyPeerSummaryCounterTags(rawValue: 1 << 1)
public static let channels = LegacyPeerSummaryCounterTags(rawValue: 1 << 2)
public func makeIterator() -> AnyIterator<LegacyPeerSummaryCounterTags> {
var index = 0
return AnyIterator { () -> LegacyPeerSummaryCounterTags? in
while index < 31 {
let currentTags = self.rawValue >> UInt32(index)
let tag = LegacyPeerSummaryCounterTags(rawValue: 1 << UInt32(index))
index += 1
if currentTags == 0 {
break
}
if (currentTags & 1) != 0 {
return tag
}
}
return nil
}
}
}
public extension PeerSummaryCounterTags {
static let contact = PeerSummaryCounterTags(rawValue: 1 << 3)
static let nonContact = PeerSummaryCounterTags(rawValue: 1 << 4)
static let group = PeerSummaryCounterTags(rawValue: 1 << 5)
static let bot = PeerSummaryCounterTags(rawValue: 1 << 7)
static let channel = PeerSummaryCounterTags(rawValue: 1 << 8)
static let all: PeerSummaryCounterTags = [
.contact,
.nonContact,
.group,
.bot,
.channel
]
}
private enum PreferencesKeyValues: Int32 {
case globalNotifications = 0
case suggestedLocalization = 3
case limitsConfiguration = 4
case contentPrivacySettings = 8
case networkSettings = 9
case remoteStorageConfiguration = 10
case voipConfiguration = 11
case appChangelogState = 12
case localizationListState = 13
case appConfiguration = 14
case searchBotsConfiguration = 15
case contactsSettings = 16
case contentSettings = 19
case chatListFilters = 20
case peersNearby = 21
case chatListFiltersFeaturedState = 22
case secretChatSettings = 23
case reactionSettings = 24
case premiumPromo = 26
case globalMessageAutoremoveTimeoutSettings = 27
case accountSpecificCacheStorageSettings = 28
case linksConfiguration = 29
case chatListFilterUpdates = 30
case globalPrivacySettings = 31
case storiesConfiguration = 32
case audioTranscriptionTrialState = 33
case didCacheSavedMessageTagsPrefix = 34
case displaySavedChatsAsTopics = 35
case shortcutMessages = 37
case timezoneList = 38
case botBiometricsState = 39
case businessLinks = 40
case starGifts = 41
case botStorageState = 42
case secureBotStorageState = 43
case serverSuggestionInfo = 44
case persistentChatInterfaceData = 45
case globalPostSearchState = 46
case savedMusicIds = 47
}
public func applicationSpecificPreferencesKey(_ value: Int32) -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: value + 1000)
return key
}
public func applicationSpecificSharedDataKey(_ value: Int32) -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: value + 1000)
return key
}
public struct PreferencesKeys {
public static let globalNotifications: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.globalNotifications.rawValue)
return key
}()
public static let suggestedLocalization: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.suggestedLocalization.rawValue)
return key
}()
public static let limitsConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.limitsConfiguration.rawValue)
return key
}()
public static let contentPrivacySettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.contentPrivacySettings.rawValue)
return key
}()
public static let networkSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.networkSettings.rawValue)
return key
}()
public static let remoteStorageConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.remoteStorageConfiguration.rawValue)
return key
}()
public static let voipConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.voipConfiguration.rawValue)
return key
}()
public static let appChangelogState: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.appChangelogState.rawValue)
return key
}()
public static let localizationListState: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.localizationListState.rawValue)
return key
}()
public static let appConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.appConfiguration.rawValue)
return key
}()
public static let searchBotsConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.searchBotsConfiguration.rawValue)
return key
}()
public static let contactsSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.contactsSettings.rawValue)
return key
}()
public static let secretChatSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.secretChatSettings.rawValue)
return key
}()
public static let contentSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.contentSettings.rawValue)
return key
}()
public static let chatListFilters: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.chatListFilters.rawValue)
return key
}()
public static let peersNearby: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.peersNearby.rawValue)
return key
}()
public static let chatListFiltersFeaturedState: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.chatListFiltersFeaturedState.rawValue)
return key
}()
public static let reactionSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.reactionSettings.rawValue)
return key
}()
public static let premiumPromo: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.premiumPromo.rawValue)
return key
}()
public static let globalMessageAutoremoveTimeoutSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.globalMessageAutoremoveTimeoutSettings.rawValue)
return key
}()
public static let accountSpecificCacheStorageSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.accountSpecificCacheStorageSettings.rawValue)
return key
}()
public static let linksConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.linksConfiguration.rawValue)
return key
}()
public static let chatListFilterUpdates: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.chatListFilterUpdates.rawValue)
return key
}()
public static let globalPrivacySettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.globalPrivacySettings.rawValue)
return key
}()
public static let storiesConfiguration: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.storiesConfiguration.rawValue)
return key
}()
public static let audioTranscriptionTrialState: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.audioTranscriptionTrialState.rawValue)
return key
}()
public static func didCacheSavedMessageTags(threadId: Int64?) -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.didCacheSavedMessageTagsPrefix.rawValue)
key.setInt64(4, value: threadId ?? 0)
return key
}
public static func displaySavedChatsAsTopics() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.displaySavedChatsAsTopics.rawValue)
return key
}
public static func shortcutMessages() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.shortcutMessages.rawValue)
return key
}
public static func timezoneList() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.timezoneList.rawValue)
return key
}
static func botBiometricsStatePrefix() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.botBiometricsState.rawValue)
return key
}
static func extractBotBiometricsStatePeerId(key: ValueBoxKey) -> PeerId? {
if key.length != 4 + 8 {
return nil
}
if key.getInt32(0) != PreferencesKeyValues.botBiometricsState.rawValue {
return nil
}
return PeerId(key.getInt64(4))
}
public static func botBiometricsState(peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.botBiometricsState.rawValue)
key.setInt64(4, value: peerId.toInt64())
return key
}
public static func businessLinks() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.businessLinks.rawValue)
return key
}
public static func starGifts() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.starGifts.rawValue)
return key
}
public static func botStorageState(peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.botStorageState.rawValue)
key.setInt64(4, value: peerId.toInt64())
return key
}
public static func secureBotStorageState() -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.secureBotStorageState.rawValue)
return key
}
public static func serverSuggestionInfo() -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.serverSuggestionInfo.rawValue)
return key
}
public static func persistentChatInterfaceData(peerId: PeerId) -> ValueBoxKey {
let key = ValueBoxKey(length: 4 + 8)
key.setInt32(0, value: PreferencesKeyValues.persistentChatInterfaceData.rawValue)
key.setInt64(4, value: peerId.toInt64())
return key
}
public static func globalPostSearchState() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.globalPostSearchState.rawValue)
return key
}
public static func savedMusicIds() -> ValueBoxKey {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: PreferencesKeyValues.savedMusicIds.rawValue)
return key
}
}
private enum SharedDataKeyValues: Int32 {
case loggingSettings = 0
case cacheStorageSettings = 2
case localizationSettings = 3
case proxySettings = 4
case autodownloadSettings = 5
case themeSettings = 6
case countriesList = 7
case wallapersState = 8
case chatThemes = 10
case deviceContacts = 11
}
public struct SharedDataKeys {
public static let loggingSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.loggingSettings.rawValue)
return key
}()
public static let cacheStorageSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.cacheStorageSettings.rawValue)
return key
}()
public static let localizationSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.localizationSettings.rawValue)
return key
}()
public static let proxySettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.proxySettings.rawValue)
return key
}()
public static let autodownloadSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.autodownloadSettings.rawValue)
return key
}()
public static let themeSettings: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.themeSettings.rawValue)
return key
}()
public static let countriesList: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.countriesList.rawValue)
return key
}()
public static let wallapersState: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.wallapersState.rawValue)
return key
}()
public static let chatThemes: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.chatThemes.rawValue)
return key
}()
public static let deviceContacts: ValueBoxKey = {
let key = ValueBoxKey(length: 4)
key.setInt32(0, value: SharedDataKeyValues.deviceContacts.rawValue)
return key
}()
}
public func applicationSpecificItemCacheCollectionId(_ value: Int8) -> Int8 {
return 64 + value
}
public func applicationSpecificOrderedItemListCollectionId(_ value: Int32) -> Int32 {
return 1000 + value
}
@@ -0,0 +1,41 @@
import Postbox
public struct NetworkSettings: Codable {
public var reducedBackupDiscoveryTimeout: Bool
public var applicationUpdateUrlPrefix: String?
public var backupHostOverride: String?
public var useNetworkFramework: Bool?
public var useExperimentalDownload: Bool?
public static var defaultSettings: NetworkSettings {
return NetworkSettings(reducedBackupDiscoveryTimeout: false, applicationUpdateUrlPrefix: nil, backupHostOverride: nil, useNetworkFramework: nil, useExperimentalDownload: nil)
}
public init(reducedBackupDiscoveryTimeout: Bool, applicationUpdateUrlPrefix: String?, backupHostOverride: String?, useNetworkFramework: Bool?, useExperimentalDownload: Bool?) {
self.reducedBackupDiscoveryTimeout = reducedBackupDiscoveryTimeout
self.applicationUpdateUrlPrefix = applicationUpdateUrlPrefix
self.backupHostOverride = backupHostOverride
self.useNetworkFramework = useNetworkFramework
self.useExperimentalDownload = useExperimentalDownload
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.reducedBackupDiscoveryTimeout = ((try? container.decode(Int32.self, forKey: "reducedBackupDiscoveryTimeout")) ?? 0) != 0
self.applicationUpdateUrlPrefix = try? container.decodeIfPresent(String.self, forKey: "applicationUpdateUrlPrefix")
self.backupHostOverride = try? container.decodeIfPresent(String.self, forKey: "backupHostOverride")
self.useNetworkFramework = try container.decodeIfPresent(Bool.self, forKey: "useNetworkFramework_v2")
self.useExperimentalDownload = try container.decodeIfPresent(Bool.self, forKey: "useExperimentalDownload_v2")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode((self.reducedBackupDiscoveryTimeout ? 1 : 0) as Int32, forKey: "reducedBackupDiscoveryTimeout")
try container.encodeIfPresent(self.applicationUpdateUrlPrefix, forKey: "applicationUpdateUrlPrefix")
try container.encodeIfPresent(self.backupHostOverride, forKey: "backupHostOverride")
try container.encodeIfPresent(self.useNetworkFramework, forKey: "useNetworkFramework_v2")
try container.encodeIfPresent(self.useExperimentalDownload, forKey: "useExperimentalDownload_v2")
}
}
@@ -0,0 +1,149 @@
import Foundation
import Postbox
import SwiftSignalKit
import TelegramApi
public final class NewSessionReview: Codable, Equatable {
struct Id {
var rawValue: MemoryBuffer
init(id: Int64) {
let buffer = WriteBuffer()
var id = id
buffer.write(&id, length: 8)
self.rawValue = buffer.makeReadBufferAndReset()
}
}
public let id: Int64
public let device: String
public let location: String
public let timestamp: Int32
public init(id: Int64, device: String, location: String, timestamp: Int32) {
self.id = id
self.device = device
self.location = location
self.timestamp = timestamp
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.id = try container.decode(Int64.self, forKey: "id")
self.device = try container.decode(String.self, forKey: "device")
self.location = try container.decode(String.self, forKey: "location")
self.timestamp = try container.decode(Int32.self, forKey: "timestamp")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.id, forKey: "id")
try container.encode(self.device, forKey: "device")
try container.encode(self.location, forKey: "location")
try container.encode(self.timestamp, forKey: "timestamp")
}
public static func ==(lhs: NewSessionReview, rhs: NewSessionReview) -> Bool {
if lhs.id != rhs.id {
return false
}
if lhs.device != rhs.device {
return false
}
if lhs.location != rhs.location {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
return true
}
}
func _internal_cleanupSessionReviews(account: Account) -> Signal<Never, NoError> {
return account.postbox.transaction { transaction -> Void in
var autoconfirmTimeout: Int32 = 7 * 24 * 60 * 60
let appConfig = currentAppConfiguration(transaction: transaction)
if let data = appConfig.data {
if let value = data["authorization_autoconfirm_period"] as? Double {
autoconfirmTimeout = Int32(round(value))
}
}
let timestamp = Int32(Date().timeIntervalSince1970)
var removeIds: [MemoryBuffer] = []
for entry in transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.NewSessionReviews) {
guard let item = entry.contents.get(NewSessionReview.self) else {
removeIds.append(entry.id)
continue
}
if item.timestamp <= timestamp - autoconfirmTimeout {
removeIds.append(entry.id)
}
}
for removeId in removeIds {
transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.NewSessionReviews, itemId: removeId)
}
}
|> ignoreValues
}
public func newSessionReviews(postbox: Postbox) -> Signal<[NewSessionReview], NoError> {
let viewKey: PostboxViewKey = .orderedItemList(id: Namespaces.OrderedItemList.NewSessionReviews)
return postbox.combinedView(keys: [viewKey])
|> mapToSignal { views -> Signal<[NewSessionReview], NoError> in
guard let view = views.views[viewKey] as? OrderedItemListView else {
return .single([])
}
var result: [NewSessionReview] = []
for item in view.items {
guard let item = item.contents.get(NewSessionReview.self) else {
continue
}
result.append(item)
}
return .single(result)
}
}
public func addNewSessionReview(postbox: Postbox, item: NewSessionReview) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
guard let entry = CodableEntry(item) else {
return
}
transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.NewSessionReviews, item: OrderedItemListEntry(id: NewSessionReview.Id(id: item.id).rawValue, contents: entry), removeTailIfCountExceeds: 200)
}
|> ignoreValues
}
public func clearNewSessionReviews(postbox: Postbox) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.NewSessionReviews, items: [])
}
|> ignoreValues
}
public func removeNewSessionReviews(postbox: Postbox, ids: [Int64]) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
for id in ids {
transaction.removeOrderedItemListItem(collectionId: Namespaces.OrderedItemList.NewSessionReviews, itemId: NewSessionReview.Id(id: id).rawValue)
}
}
|> ignoreValues
}
func _internal_confirmNewSessionReview(account: Account, id: Int64) -> Signal<Never, NoError> {
return account.network.request(Api.functions.account.changeAuthorizationSettings(flags: 1 << 3, hash: id, encryptedRequestsDisabled: nil, callRequestsDisabled: nil))
|> `catch` { _ -> Signal<Api.Bool, NoError> in
return .single(.boolFalse)
}
|> ignoreValues
}
@@ -0,0 +1,16 @@
import Foundation
import Postbox
public class NonPremiumMessageAttribute: MessageAttribute {
public var associatedMessageIds: [MessageId] = []
public init() {
}
required public init(decoder: PostboxDecoder) {
}
public func encode(_ encoder: PostboxEncoder) {
}
}
@@ -0,0 +1,34 @@
import Foundation
import Postbox
public struct NotificationInfoMessageAttributeFlags: OptionSet {
public var rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public init() {
self.rawValue = 0
}
public static let muted = NotificationInfoMessageAttributeFlags(rawValue: 1 << 0)
public static let personal = NotificationInfoMessageAttributeFlags(rawValue: 1 << 1)
public static let automaticMessage = NotificationInfoMessageAttributeFlags(rawValue: 1 << 2)
}
public class NotificationInfoMessageAttribute: MessageAttribute {
public let flags: NotificationInfoMessageAttributeFlags
public init(flags: NotificationInfoMessageAttributeFlags) {
self.flags = flags
}
required public init(decoder: PostboxDecoder) {
self.flags = NotificationInfoMessageAttributeFlags(rawValue: decoder.decodeInt32ForKey("f", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.flags.rawValue, forKey: "f")
}
}
@@ -0,0 +1,34 @@
import Foundation
import Postbox
public class OutgoingChatContextResultMessageAttribute: MessageAttribute {
public let queryId: Int64
public let id: String
public let hideVia: Bool
public let webpageUrl: String?
public init(queryId: Int64, id: String, hideVia: Bool, webpageUrl: String?) {
self.queryId = queryId
self.id = id
self.hideVia = hideVia
self.webpageUrl = webpageUrl
}
required public init(decoder: PostboxDecoder) {
self.queryId = decoder.decodeInt64ForKey("q", orElse: 0)
self.id = decoder.decodeStringForKey("i", orElse: "")
self.hideVia = decoder.decodeBoolForKey("v", orElse: false)
self.webpageUrl = decoder.decodeOptionalStringForKey("wurl")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.queryId, forKey: "q")
encoder.encodeString(self.id, forKey: "i")
encoder.encodeBool(self.hideVia, forKey: "v")
if let webpageUrl = self.webpageUrl {
encoder.encodeString(webpageUrl, forKey: "wurl")
} else {
encoder.encodeNil(forKey: "wurl")
}
}
}
@@ -0,0 +1,36 @@
import Foundation
import Postbox
public struct OutgoingContentInfoFlags: OptionSet {
public var rawValue: Int32
public init() {
self.rawValue = 0
}
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let disableLinkPreviews = OutgoingContentInfoFlags(rawValue: 1 << 0)
}
public class OutgoingContentInfoMessageAttribute: MessageAttribute {
public let flags: OutgoingContentInfoFlags
public init(flags: OutgoingContentInfoFlags) {
self.flags = flags
}
required public init(decoder: PostboxDecoder) {
self.flags = OutgoingContentInfoFlags(rawValue: decoder.decodeInt32ForKey("f", orElse: 0))
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.flags.rawValue, forKey: "f")
}
public func withUpdatedFlags(_ flags: OutgoingContentInfoFlags) -> OutgoingContentInfoMessageAttribute {
return OutgoingContentInfoMessageAttribute(flags: flags)
}
}
@@ -0,0 +1,78 @@
import Foundation
import Postbox
public struct OutgoingMessageInfoFlags: OptionSet {
public var rawValue: Int32
public init() {
self.rawValue = 0
}
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static var transformedMedia = OutgoingMessageInfoFlags(rawValue: 1 << 0)
}
public class OutgoingMessageInfoAttribute: MessageAttribute {
public let uniqueId: Int64
public let flags: OutgoingMessageInfoFlags
public let acknowledged: Bool
public let correlationId: Int64?
public let bubbleUpEmojiOrStickersets: [ItemCollectionId]
public let partialReference: PartialMediaReference?
public init(uniqueId: Int64, flags: OutgoingMessageInfoFlags, acknowledged: Bool, correlationId: Int64?, bubbleUpEmojiOrStickersets: [ItemCollectionId], partialReference: PartialMediaReference?) {
self.uniqueId = uniqueId
self.flags = flags
self.acknowledged = acknowledged
self.correlationId = correlationId
self.bubbleUpEmojiOrStickersets = bubbleUpEmojiOrStickersets
self.partialReference = partialReference
}
required public init(decoder: PostboxDecoder) {
self.uniqueId = decoder.decodeInt64ForKey("u", orElse: 0)
self.flags = OutgoingMessageInfoFlags(rawValue: decoder.decodeInt32ForKey("f", orElse: 0))
self.acknowledged = decoder.decodeInt32ForKey("ack", orElse: 0) != 0
self.correlationId = decoder.decodeOptionalInt64ForKey("cid")
if let data = decoder.decodeDataForKey("bubbleUpEmojiOrStickersets") {
self.bubbleUpEmojiOrStickersets = ItemCollectionId.decodeArrayFromBuffer(ReadBuffer(data: data))
} else {
self.bubbleUpEmojiOrStickersets = []
}
if let partialReference = decoder.decodeAnyObjectForKey("partialReference", decoder: { PartialMediaReference(decoder: $0) }) as? PartialMediaReference {
self.partialReference = partialReference
} else {
self.partialReference = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt64(self.uniqueId, forKey: "u")
encoder.encodeInt32(self.flags.rawValue, forKey: "f")
encoder.encodeInt32(self.acknowledged ? 1 : 0, forKey: "ack")
if let correlationId = self.correlationId {
encoder.encodeInt64(correlationId, forKey: "cid")
} else {
encoder.encodeNil(forKey: "cid")
}
let bubbleUpEmojiOrStickersetsBuffer = WriteBuffer()
ItemCollectionId.encodeArrayToBuffer(self.bubbleUpEmojiOrStickersets, buffer: bubbleUpEmojiOrStickersetsBuffer)
encoder.encodeData(bubbleUpEmojiOrStickersetsBuffer.makeData(), forKey: "bubbleUpEmojiOrStickersets")
if let partialReference {
encoder.encodeObjectWithEncoder(partialReference, encoder: partialReference.encode, forKey: "partialReference")
} else {
encoder.encodeNil(forKey: "partialReference")
}
}
public func withUpdatedFlags(_ flags: OutgoingMessageInfoFlags) -> OutgoingMessageInfoAttribute {
return OutgoingMessageInfoAttribute(uniqueId: self.uniqueId, flags: flags, acknowledged: self.acknowledged, correlationId: self.correlationId, bubbleUpEmojiOrStickersets: self.bubbleUpEmojiOrStickersets, partialReference: self.partialReference)
}
public func withUpdatedAcknowledged(_ acknowledged: Bool) -> OutgoingMessageInfoAttribute {
return OutgoingMessageInfoAttribute(uniqueId: self.uniqueId, flags: self.flags, acknowledged: acknowledged, correlationId: self.correlationId, bubbleUpEmojiOrStickersets: self.bubbleUpEmojiOrStickersets, partialReference: self.partialReference)
}
}
@@ -0,0 +1,58 @@
import Foundation
import Postbox
public let scheduleWhenOnlineTimestamp: Int32 = 0x7ffffffe
public class OutgoingScheduleInfoMessageAttribute: MessageAttribute {
public let scheduleTime: Int32
public let repeatPeriod: Int32?
public init(scheduleTime: Int32, repeatPeriod: Int32?) {
self.scheduleTime = scheduleTime
self.repeatPeriod = repeatPeriod
}
required public init(decoder: PostboxDecoder) {
self.scheduleTime = decoder.decodeInt32ForKey("t", orElse: 0)
self.repeatPeriod = decoder.decodeOptionalInt32ForKey("rp")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.scheduleTime, forKey: "t")
if let repeatPeriod = self.repeatPeriod {
encoder.encodeInt32(repeatPeriod, forKey: "rp")
} else {
encoder.encodeNil(forKey: "rp")
}
}
public func withUpdatedScheduleTime(_ scheduleTime: Int32) -> OutgoingScheduleInfoMessageAttribute {
return OutgoingScheduleInfoMessageAttribute(scheduleTime: scheduleTime, repeatPeriod: self.repeatPeriod)
}
public func withUpdatedRepeatPeriod(_ repeatPeriod: Int32?) -> OutgoingScheduleInfoMessageAttribute {
return OutgoingScheduleInfoMessageAttribute(scheduleTime: self.scheduleTime, repeatPeriod: repeatPeriod)
}
}
public extension Message {
var scheduleTime: Int32? {
for attribute in self.attributes {
if let attribute = attribute as? OutgoingScheduleInfoMessageAttribute {
return attribute.scheduleTime
}
}
return nil
}
var scheduleRepeatPeriod: Int32? {
for attribute in self.attributes {
if let attribute = attribute as? OutgoingScheduleInfoMessageAttribute {
return attribute.repeatPeriod
} else if let attribute = attribute as? ScheduledRepeatAttribute {
return attribute.repeatPeriod
}
}
return nil
}
}
@@ -0,0 +1,57 @@
import Foundation
import FlatBuffers
import FlatSerialization
public enum TelegramPeerAccessHash: Hashable {
case personal(Int64)
case genericPublic(Int64)
public var value: Int64 {
switch self {
case let .personal(personal):
return personal
case let .genericPublic(genericPublic):
return genericPublic
}
}
public init(flatBuffersObject: TelegramCore_TelegramPeerAccessHash) throws {
switch flatBuffersObject.valueType {
case .telegrampeeraccesshashPersonal:
guard let personal = flatBuffersObject.value(type: TelegramCore_TelegramPeerAccessHash_Personal.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .personal(personal.accessHash)
case .telegrampeeraccesshashGenericpublic:
guard let genericPublic = flatBuffersObject.value(type: TelegramCore_TelegramPeerAccessHash_GenericPublic.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .genericPublic(genericPublic.accessHash)
case .none_:
throw FlatBuffersError.missingRequiredField()
}
}
public func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset {
let valueType: TelegramCore_TelegramPeerAccessHash_Value
let valueOffset: Offset
switch self {
case let .personal(accessHash):
valueType = .telegrampeeraccesshashPersonal
let start = TelegramCore_TelegramPeerAccessHash_Personal.startTelegramPeerAccessHash_Personal(&builder)
TelegramCore_TelegramPeerAccessHash_Personal.add(accessHash: accessHash, &builder)
valueOffset = TelegramCore_TelegramPeerAccessHash_Personal.endTelegramPeerAccessHash_Personal(&builder, start: start)
case let .genericPublic(accessHash):
valueType = .telegrampeeraccesshashGenericpublic
let start = TelegramCore_TelegramPeerAccessHash_GenericPublic.startTelegramPeerAccessHash_GenericPublic(&builder)
TelegramCore_TelegramPeerAccessHash_GenericPublic.add(accessHash: accessHash, &builder)
valueOffset = TelegramCore_TelegramPeerAccessHash_GenericPublic.endTelegramPeerAccessHash_GenericPublic(&builder, start: start)
}
let start = TelegramCore_TelegramPeerAccessHash.startTelegramPeerAccessHash(&builder)
TelegramCore_TelegramPeerAccessHash.add(valueType: valueType, &builder)
TelegramCore_TelegramPeerAccessHash.add(value: valueOffset, &builder)
return TelegramCore_TelegramPeerAccessHash.endTelegramPeerAccessHash(&builder, start: start)
}
}
@@ -0,0 +1,101 @@
import Postbox
import FlatBuffers
import FlatSerialization
public final class RestrictionRule: PostboxCoding, Equatable {
public let platform: String
public let reason: String
public let text: String
public init(platform: String, reason: String, text: String) {
self.platform = platform
self.reason = reason
self.text = text
}
public init(platform: String) {
self.platform = platform
self.reason = ""
self.text = ""
}
public init(decoder: PostboxDecoder) {
self.platform = decoder.decodeStringForKey("p", orElse: "all")
self.reason = decoder.decodeStringForKey("r", orElse: "")
self.text = decoder.decodeStringForKey("t", orElse: "")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.platform, forKey: "p")
encoder.encodeString(self.reason, forKey: "r")
encoder.encodeString(self.text, forKey: "t")
}
public static func ==(lhs: RestrictionRule, rhs: RestrictionRule) -> Bool {
if lhs.platform != rhs.platform {
return false
}
if lhs.reason != rhs.reason {
return false
}
if lhs.text != rhs.text {
return false
}
return true
}
public init(flatBuffersObject: TelegramCore_RestrictionRule) throws {
self.platform = flatBuffersObject.platform
self.reason = flatBuffersObject.reason
self.text = flatBuffersObject.text
}
public func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset {
let platformOffset = builder.create(string: self.platform)
let reasonOffset = builder.create(string: self.reason)
let textOffset = builder.create(string: self.text)
let start = TelegramCore_RestrictionRule.startRestrictionRule(&builder)
TelegramCore_RestrictionRule.add(platform: platformOffset, &builder)
TelegramCore_RestrictionRule.add(reason: reasonOffset, &builder)
TelegramCore_RestrictionRule.add(text: textOffset, &builder)
return TelegramCore_RestrictionRule.endRestrictionRule(&builder, start: start)
}
}
public final class PeerAccessRestrictionInfo: PostboxCoding, Equatable {
public let rules: [RestrictionRule]
public init(rules: [RestrictionRule]) {
self.rules = rules
}
public init(decoder: PostboxDecoder) {
if let value = decoder.decodeOptionalStringForKey("rsn") {
self.rules = [RestrictionRule(platform: "all", reason: "", text: value)]
} else {
self.rules = decoder.decodeObjectArrayWithDecoderForKey("rs")
}
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectArray(self.rules, forKey: "rs")
}
public static func ==(lhs: PeerAccessRestrictionInfo, rhs: PeerAccessRestrictionInfo) -> Bool {
return lhs.rules == rhs.rules
}
public init(flatBuffersObject: TelegramCore_PeerAccessRestrictionInfo) throws {
self.rules = try (0 ..< flatBuffersObject.rulesCount).map { try RestrictionRule(flatBuffersObject: flatBuffersObject.rules(at: $0)!) }
}
public func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset {
let rulesOffsets = self.rules.map { $0.encodeToFlatBuffers(builder: &builder) }
let rulesOffset = builder.createVector(ofOffsets: rulesOffsets, len: rulesOffsets.count)
let start = TelegramCore_PeerAccessRestrictionInfo.startPeerAccessRestrictionInfo(&builder)
TelegramCore_PeerAccessRestrictionInfo.addVectorOf(rules: rulesOffset, &builder)
return TelegramCore_PeerAccessRestrictionInfo.endPeerAccessRestrictionInfo(&builder, start: start)
}
}
@@ -0,0 +1,19 @@
import Foundation
import Postbox
public class PeerGroupMessageStateVersionAttribute: MessageAttribute {
public let stateIndex: Int32
public init(stateIndex: Int32) {
self.stateIndex = stateIndex
}
required public init(decoder: PostboxDecoder) {
self.stateIndex = decoder.decodeInt32ForKey("p", orElse: 0)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.stateIndex, forKey: "p")
}
}
@@ -0,0 +1,122 @@
import Postbox
import FlatBuffers
import FlatSerialization
public enum PeerReference: PostboxCoding, Hashable, Equatable {
case user(id: Int64, accessHash: Int64)
case group(id: Int64)
case channel(id: Int64, accessHash: Int64)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("_r", orElse: 0) {
case 0:
let id: Int64
if let idValue = decoder.decodeOptionalInt64ForKey("i") {
id = idValue
} else {
id = Int64(decoder.decodeInt32ForKey("i", orElse: 0))
}
self = .user(id: id, accessHash: decoder.decodeInt64ForKey("h", orElse: 0))
case 1:
let id: Int64
if let idValue = decoder.decodeOptionalInt64ForKey("i") {
id = idValue
} else {
id = Int64(decoder.decodeInt32ForKey("i", orElse: 0))
}
self = .group(id: id)
case 2:
let id: Int64
if let idValue = decoder.decodeOptionalInt64ForKey("i") {
id = idValue
} else {
id = Int64(decoder.decodeInt32ForKey("i", orElse: 0))
}
self = .channel(id: id, accessHash: decoder.decodeInt64ForKey("h", orElse: 0))
default:
assertionFailure()
self = .user(id: 0, accessHash: 0)
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .user(id, accessHash):
encoder.encodeInt32(0, forKey: "_r")
encoder.encodeInt64(id, forKey: "i")
encoder.encodeInt64(accessHash, forKey: "h")
case let .group(id):
encoder.encodeInt32(1, forKey: "_r")
encoder.encodeInt64(id, forKey: "i")
case let .channel(id, accessHash):
encoder.encodeInt32(2, forKey: "_r")
encoder.encodeInt64(id, forKey: "i")
encoder.encodeInt64(accessHash, forKey: "h")
}
}
public init?(_ peer: Peer) {
switch peer {
case let user as TelegramUser:
if let accessHash = user.accessHash {
self = .user(id: user.id.id._internalGetInt64Value(), accessHash: accessHash.value)
} else {
return nil
}
case let group as TelegramGroup:
self = .group(id: group.id.id._internalGetInt64Value())
case let channel as TelegramChannel:
if let accessHash = channel.accessHash {
self = .channel(id: channel.id.id._internalGetInt64Value(), accessHash: accessHash.value)
} else {
return nil
}
default:
return nil
}
}
public init(flatBuffersObject: TelegramCore_PeerReference) throws {
switch flatBuffersObject.valueType {
case .peerreferenceUser:
guard let value = flatBuffersObject.value(type: TelegramCore_PeerReference_User.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .user(id: value.id, accessHash: value.accessHash)
case .peerreferenceGroup:
guard let value = flatBuffersObject.value(type: TelegramCore_PeerReference_Group.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .group(id: value.id)
case .peerreferenceChannel:
guard let value = flatBuffersObject.value(type: TelegramCore_PeerReference_Channel.self) else {
throw FlatBuffersError.missingRequiredField()
}
self = .channel(id: value.id, accessHash: value.accessHash)
case .none_:
throw FlatBuffersError.missingRequiredField()
}
}
public func encodeToFlatBuffers(builder: inout FlatBufferBuilder) -> Offset {
switch self {
case let .user(id, accessHash):
let start = TelegramCore_PeerReference.startPeerReference(&builder)
TelegramCore_PeerReference_User.add(id: id, &builder)
TelegramCore_PeerReference_User.add(accessHash: accessHash, &builder)
let offset = TelegramCore_PeerReference_User.endPeerReference_User(&builder, start: start)
return TelegramCore_PeerReference.createPeerReference(&builder, valueType: .peerreferenceUser, valueOffset: offset)
case let .group(id):
let start = TelegramCore_PeerReference.startPeerReference(&builder)
TelegramCore_PeerReference_Group.add(id: id, &builder)
let offset = TelegramCore_PeerReference_Group.endPeerReference_Group(&builder, start: start)
return TelegramCore_PeerReference.createPeerReference(&builder, valueType: .peerreferenceGroup, valueOffset: offset)
case let .channel(id, accessHash):
let start = TelegramCore_PeerReference.startPeerReference(&builder)
TelegramCore_PeerReference_Channel.add(id: id, &builder)
TelegramCore_PeerReference_Channel.add(accessHash: accessHash, &builder)
let offset = TelegramCore_PeerReference_Channel.endPeerReference_Channel(&builder, start: start)
return TelegramCore_PeerReference.createPeerReference(&builder, valueType: .peerreferenceChannel, valueOffset: offset)
}
}
}
@@ -0,0 +1,157 @@
import Postbox
public struct PeerStatusSettings: PostboxCoding, Equatable {
public struct Flags: OptionSet {
public var rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public static let canReport = Flags(rawValue: 1 << 1)
public static let canShareContact = Flags(rawValue: 1 << 2)
public static let canBlock = Flags(rawValue: 1 << 3)
public static let canAddContact = Flags(rawValue: 1 << 4)
public static let addExceptionWhenAddingContact = Flags(rawValue: 1 << 5)
public static let autoArchived = Flags(rawValue: 1 << 7)
public static let suggestAddMembers = Flags(rawValue: 1 << 8)
}
public struct ManagingBot: Codable, Equatable {
public var id: PeerId
public var manageUrl: String?
public var isPaused: Bool
public var canReply: Bool
public init(id: PeerId, manageUrl: String?, isPaused: Bool, canReply: Bool) {
self.id = id
self.manageUrl = manageUrl
self.isPaused = isPaused
self.canReply = canReply
}
}
public var flags: PeerStatusSettings.Flags
public var geoDistance: Int32?
public var requestChatTitle: String?
public var requestChatDate: Int32?
public var requestChatIsChannel: Bool?
public var managingBot: ManagingBot?
public var paidMessageStars: StarsAmount?
public var registrationDate: String?
public var phoneCountry: String?
public var nameChangeDate: Int32?
public var photoChangeDate: Int32?
public init() {
self.flags = PeerStatusSettings.Flags()
self.geoDistance = nil
self.requestChatTitle = nil
self.requestChatDate = nil
self.managingBot = nil
self.paidMessageStars = nil
self.registrationDate = nil
self.phoneCountry = nil
self.nameChangeDate = nil
self.photoChangeDate = nil
}
public init(
flags: PeerStatusSettings.Flags,
geoDistance: Int32? = nil,
requestChatTitle: String? = nil,
requestChatDate: Int32? = nil,
requestChatIsChannel: Bool? = nil,
managingBot: ManagingBot? = nil,
paidMessageStars: StarsAmount? = nil,
registrationDate: String? = nil,
phoneCountry: String? = nil,
nameChangeDate: Int32? = nil,
photoChangeDate: Int32? = nil
) {
self.flags = flags
self.geoDistance = geoDistance
self.requestChatTitle = requestChatTitle
self.requestChatDate = requestChatDate
self.requestChatIsChannel = requestChatIsChannel
self.managingBot = managingBot
self.paidMessageStars = paidMessageStars
self.registrationDate = registrationDate
self.phoneCountry = phoneCountry
self.nameChangeDate = nameChangeDate
self.photoChangeDate = photoChangeDate
}
public init(decoder: PostboxDecoder) {
self.flags = Flags(rawValue: decoder.decodeInt32ForKey("flags", orElse: 0))
self.geoDistance = decoder.decodeOptionalInt32ForKey("geoDistance")
self.requestChatTitle = decoder.decodeOptionalStringForKey("requestChatTitle")
self.requestChatDate = decoder.decodeOptionalInt32ForKey("requestChatDate")
self.requestChatIsChannel = decoder.decodeOptionalBoolForKey("requestChatIsChannel")
self.managingBot = decoder.decodeCodable(ManagingBot.self, forKey: "managingBot")
self.paidMessageStars = decoder.decodeCodable(StarsAmount.self, forKey: "paidMessageStars")
self.registrationDate = decoder.decodeOptionalStringForKey("registrationDate")
self.phoneCountry = decoder.decodeOptionalStringForKey("phoneCountry")
self.nameChangeDate = decoder.decodeOptionalInt32ForKey("nameChangeDate")
self.photoChangeDate = decoder.decodeOptionalInt32ForKey("photoChangeDate")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeInt32(self.flags.rawValue, forKey: "flags")
if let geoDistance = self.geoDistance {
encoder.encodeInt32(geoDistance, forKey: "geoDistance")
} else {
encoder.encodeNil(forKey: "geoDistance")
}
if let requestChatTitle = self.requestChatTitle {
encoder.encodeString(requestChatTitle, forKey: "requestChatTitle")
} else {
encoder.encodeNil(forKey: "requestChatTitle")
}
if let requestChatDate = self.requestChatDate {
encoder.encodeInt32(requestChatDate, forKey: "requestChatDate")
} else {
encoder.encodeNil(forKey: "requestChatDate")
}
if let requestChatIsChannel = self.requestChatIsChannel {
encoder.encodeBool(requestChatIsChannel, forKey: "requestChatIsChannel")
} else {
encoder.encodeNil(forKey: "requestChatIsChannel")
}
if let managingBot = self.managingBot {
encoder.encodeCodable(managingBot, forKey: "managingBot")
} else {
encoder.encodeNil(forKey: "managingBot")
}
if let paidMessageStars = self.paidMessageStars {
encoder.encodeCodable(paidMessageStars, forKey: "paidMessageStars")
} else {
encoder.encodeNil(forKey: "paidMessageStars")
}
if let registrationDate = self.registrationDate {
encoder.encodeString(registrationDate, forKey: "registrationDate")
} else {
encoder.encodeNil(forKey: "registrationDate")
}
if let phoneCountry = self.phoneCountry {
encoder.encodeString(phoneCountry, forKey: "phoneCountry")
} else {
encoder.encodeNil(forKey: "phoneCountry")
}
if let nameChangeDate = self.nameChangeDate {
encoder.encodeInt32(nameChangeDate, forKey: "nameChangeDate")
} else {
encoder.encodeNil(forKey: "nameChangeDate")
}
if let photoChangeDate = self.photoChangeDate {
encoder.encodeInt32(photoChangeDate, forKey: "photoChangeDate")
} else {
encoder.encodeNil(forKey: "photoChangeDate")
}
}
public func contains(_ member: PeerStatusSettings.Flags) -> Bool {
return self.flags.contains(member)
}
}
@@ -0,0 +1,23 @@
#if os(iOS)
import UIKit
#endif
public struct PixelDimensions: Equatable {
public let width: Int32
public let height: Int32
public init(width: Int32, height: Int32) {
self.width = width
self.height = height
}
#if os(iOS)
public init(_ size: CGSize) {
self.init(width: Int32(size.width), height: Int32(size.height))
}
public var cgSize: CGSize {
return CGSize(width: CGFloat(self.width), height: CGFloat(self.height))
}
#endif
}
@@ -0,0 +1,139 @@
import Foundation
import Postbox
public struct PremiumPromoConfiguration: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case status
case statusEntities
case videos
case premiumProductOptions
}
private struct DictionaryPair: Codable {
var key: String
var value: TelegramMediaFile
init(_ key: String, value: TelegramMediaFile) {
self.key = key
self.value = value
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.key = try container.decode(String.self, forKey: "k")
self.value = try container.decode(TelegramMediaFile.self, forKey: "v")
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.key, forKey: "k")
try container.encode(self.value, forKey: "v")
}
}
public struct PremiumProductOption: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case isCurrent
case months
case currency
case amount
case botUrl
case transactionId
case availableForUpgrade
case storeProductId
}
public let isCurrent: Bool
public let months: Int32
public let currency: String
public let amount: Int64
public let botUrl: String
public let transactionId: String?
public let availableForUpgrade: Bool
public let storeProductId: String?
public init(isCurrent: Bool, months: Int32, currency: String, amount: Int64, botUrl: String, transactionId: String?, availableForUpgrade: Bool, storeProductId: String?) {
self.isCurrent = isCurrent
self.months = months
self.currency = currency
self.amount = amount
self.botUrl = botUrl
self.transactionId = transactionId
self.availableForUpgrade = availableForUpgrade
self.storeProductId = storeProductId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.isCurrent = try container.decode(Bool.self, forKey: .isCurrent)
self.months = try container.decode(Int32.self, forKey: .months)
self.currency = try container.decode(String.self, forKey: .currency)
self.amount = try container.decode(Int64.self, forKey: .amount)
self.botUrl = try container.decode(String.self, forKey: .botUrl)
self.transactionId = try container.decodeIfPresent(String.self, forKey: .transactionId)
self.availableForUpgrade = try container.decode(Bool.self, forKey: .availableForUpgrade)
self.storeProductId = try container.decodeIfPresent(String.self, forKey: .storeProductId)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.isCurrent, forKey: .isCurrent)
try container.encode(self.months, forKey: .months)
try container.encode(self.currency, forKey: .currency)
try container.encode(self.amount, forKey: .amount)
try container.encode(self.botUrl, forKey: .botUrl)
try container.encodeIfPresent(self.transactionId, forKey: .transactionId)
try container.encode(self.availableForUpgrade, forKey: .availableForUpgrade)
try container.encodeIfPresent(self.storeProductId, forKey: .storeProductId)
}
}
public var status: String
public var statusEntities: [MessageTextEntity]
public var videos: [String: TelegramMediaFile]
public var premiumProductOptions: [PremiumProductOption]
public static var defaultValue: PremiumPromoConfiguration {
return PremiumPromoConfiguration(status: "", statusEntities: [], videos: [:], premiumProductOptions: [])
}
init(status: String, statusEntities: [MessageTextEntity], videos: [String: TelegramMediaFile], premiumProductOptions: [PremiumProductOption]) {
self.status = status
self.statusEntities = statusEntities
self.videos = videos
self.premiumProductOptions = premiumProductOptions
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.status = try container.decode(String.self, forKey: .status)
self.statusEntities = try container.decode([MessageTextEntity].self, forKey: .statusEntities)
var videos: [String: TelegramMediaFile] = [:]
let pairs = try container.decode([DictionaryPair].self, forKey: .videos)
for pair in pairs {
videos[pair.key] = pair.value
}
self.videos = videos
self.premiumProductOptions = try container.decode([PremiumProductOption].self, forKey: .premiumProductOptions)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.status, forKey: .status)
try container.encode(self.statusEntities, forKey: .statusEntities)
var pairs: [DictionaryPair] = []
for (key, file) in self.videos {
pairs.append(DictionaryPair(key, value: file))
}
try container.encode(pairs, forKey: .videos)
try container.encode(self.premiumProductOptions, forKey: .premiumProductOptions)
}
}
@@ -0,0 +1,116 @@
import Foundation
import Postbox
public enum ProxyServerConnection: Equatable, Hashable, Codable {
case socks5(username: String?, password: String?)
case mtp(secret: Data)
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
switch try container.decode(Int32.self, forKey: "_t") {
case 0:
self = .socks5(username: try container.decodeIfPresent(String.self, forKey: "username"), password: try container.decodeIfPresent(String.self, forKey: "password"))
case 1:
self = .mtp(secret: try container.decode(Data.self, forKey: "secret"))
default:
self = .socks5(username: nil, password: nil)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self {
case let .socks5(username, password):
try container.encode(0 as Int32, forKey: "_t")
try container.encodeIfPresent(username, forKey: "username")
try container.encodeIfPresent(password, forKey: "password")
case let .mtp(secret):
try container.encode(1 as Int32, forKey: "_t")
try container.encode(secret, forKey: "secret")
}
}
}
public struct ProxyServerSettings: Codable, Equatable, Hashable {
public let host: String
public let port: Int32
public let connection: ProxyServerConnection
public init(host: String, port: Int32, connection: ProxyServerConnection) {
self.host = host
self.port = port
self.connection = connection
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.host = (try? container.decode(String.self, forKey: "host")) ?? ""
self.port = (try? container.decode(Int32.self, forKey: "port")) ?? 0
if let username = try container.decodeIfPresent(String.self, forKey: "username") {
self.connection = .socks5(username: username, password: try container.decodeIfPresent(String.self, forKey: "password"))
} else {
self.connection = (try? container.decodeIfPresent(ProxyServerConnection.self, forKey: "connection")) ?? ProxyServerConnection.socks5(username: nil, password: nil)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.host, forKey: "host")
try container.encode(self.port, forKey: "port")
try container.encode(self.connection, forKey: "connection")
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.host)
hasher.combine(self.port)
hasher.combine(self.connection)
}
}
public struct ProxySettings: Codable, Equatable {
public var enabled: Bool
public var servers: [ProxyServerSettings]
public var activeServer: ProxyServerSettings?
public var useForCalls: Bool
public static var defaultSettings: ProxySettings {
return ProxySettings(enabled: false, servers: [], activeServer: nil, useForCalls: false)
}
public init(enabled: Bool, servers: [ProxyServerSettings], activeServer: ProxyServerSettings?, useForCalls: Bool) {
self.enabled = enabled
self.servers = servers
self.activeServer = activeServer
self.useForCalls = useForCalls
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.enabled = ((try? container.decode(Int32.self, forKey: "enabled")) ?? 0) != 0
self.servers = try container.decode([ProxyServerSettings].self, forKey: "servers")
self.activeServer = try container.decodeIfPresent(ProxyServerSettings.self, forKey: "activeServer")
self.useForCalls = ((try? container.decode(Int32.self, forKey: "useForCalls")) ?? 0) != 0
}
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.servers, forKey: "servers")
try container.encodeIfPresent(self.activeServer, forKey: "activeServer")
try container.encode((self.useForCalls ? 1 : 0) as Int32, forKey: "useForCalls")
}
public var effectiveActiveServer: ProxyServerSettings? {
if self.enabled, let activeServer = self.activeServer {
return activeServer
} else {
return nil
}
}
}
@@ -0,0 +1,604 @@
import Foundation
import Postbox
import TelegramApi
public struct MessageReaction: Equatable, PostboxCoding, Codable {
#if DEBUG
public static let starsReactionId: Int64 = 5435957248314579621
#else
public static let starsReactionId: Int64 = 12340000
#endif
public enum Reaction: Hashable, Comparable, Codable, PostboxCoding {
case builtin(String)
case custom(Int64)
case stars
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let value = try container.decodeIfPresent(String.self, forKey: "v") {
self = .builtin(value)
} else if let _ = try container.decodeIfPresent(Int64.self, forKey: "star") {
self = .stars
} else {
self = .custom(try container.decode(Int64.self, forKey: "cfid"))
}
}
public init(decoder: PostboxDecoder) {
if let value = decoder.decodeOptionalStringForKey("v") {
self = .builtin(value)
} else if let _ = decoder.decodeOptionalInt64ForKey("star") {
self = .stars
} else {
self = .custom(decoder.decodeInt64ForKey("cfid", orElse: 0))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self {
case let .builtin(value):
try container.encode(value, forKey: "v")
case let .custom(fileId):
try container.encode(fileId, forKey: "cfid")
case .stars:
try container.encode(0 as Int64, forKey: "star")
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case let .builtin(value):
encoder.encodeString(value, forKey: "v")
case let .custom(fileId):
encoder.encodeInt64(fileId, forKey: "cfid")
case .stars:
encoder.encodeInt64(0, forKey: "star")
}
}
public static func <(lhs: Reaction, rhs: Reaction) -> Bool {
switch lhs {
case let .builtin(lhsValue):
switch rhs {
case let .builtin(rhsValue):
return lhsValue < rhsValue
case .custom:
return true
case .stars:
return false
}
case let .custom(lhsValue):
switch rhs {
case .builtin:
return false
case let .custom(rhsValue):
return lhsValue < rhsValue
case .stars:
return false
}
case .stars:
switch rhs {
case .builtin:
return true
case .custom:
return true
case .stars:
return false
}
}
}
}
public var value: Reaction
public var count: Int32
public var chosenOrder: Int?
public var isSelected: Bool {
return self.chosenOrder != nil
}
public init(value: Reaction, count: Int32, chosenOrder: Int?) {
self.value = value
self.count = count
self.chosenOrder = chosenOrder
}
public init(decoder: PostboxDecoder) {
if let value = decoder.decodeOptionalStringForKey("v") {
self.value = .builtin(value)
} else if let _ = decoder.decodeOptionalInt64ForKey("star") {
self.value = .stars
} else {
self.value = .custom(decoder.decodeInt64ForKey("cfid", orElse: 0))
}
self.count = decoder.decodeInt32ForKey("c", orElse: 0)
if let chosenOrder = decoder.decodeOptionalInt32ForKey("cord") {
self.chosenOrder = Int(chosenOrder)
} else if let isSelected = decoder.decodeOptionalInt32ForKey("s"), isSelected != 0 {
self.chosenOrder = 0
} else {
self.chosenOrder = nil
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let value = try container.decodeIfPresent(String.self, forKey: "v") {
self.value = .builtin(value)
} else if let _ = try container.decodeIfPresent(Int64.self, forKey: "star") {
self.value = .stars
} else {
self.value = .custom(try container.decode(Int64.self, forKey: "cfid"))
}
self.count = try container.decode(Int32.self, forKey: "c")
if let chosenOrder = try container.decodeIfPresent(Int32.self, forKey: "cord") {
self.chosenOrder = Int(chosenOrder)
} else if let isSelected = try container.decodeIfPresent(Int32.self, forKey: "s"), isSelected != 0 {
self.chosenOrder = 0
} else {
self.chosenOrder = nil
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self.value {
case let .builtin(value):
encoder.encodeString(value, forKey: "v")
case let .custom(fileId):
encoder.encodeInt64(fileId, forKey: "cfid")
case .stars:
encoder.encodeInt64(0, forKey: "star")
}
encoder.encodeInt32(self.count, forKey: "c")
if let chosenOrder = self.chosenOrder {
encoder.encodeInt32(Int32(chosenOrder), forKey: "cord")
} else {
encoder.encodeNil(forKey: "cord")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self.value {
case let .builtin(value):
try container.encode(value, forKey: "v")
case let .custom(fileId):
try container.encode(fileId, forKey: "cfid")
case .stars:
try container.encode(0 as Int64, forKey: "star")
}
try container.encode(self.count, forKey: "c")
try container.encodeIfPresent(self.chosenOrder.flatMap(Int32.init), forKey: "cord")
}
}
extension MessageReaction.Reaction {
init?(apiReaction: Api.Reaction) {
switch apiReaction {
case .reactionEmpty:
return nil
case let .reactionEmoji(emoticon):
self = .builtin(emoticon)
case let .reactionCustomEmoji(documentId):
self = .custom(documentId)
case .reactionPaid:
self = .stars
}
}
var apiReaction: Api.Reaction {
switch self {
case let .builtin(value):
return .reactionEmoji(emoticon: value)
case let .custom(fileId):
return .reactionCustomEmoji(documentId: fileId)
case .stars:
return .reactionPaid
}
}
}
public final class ReactionsMessageAttribute: Equatable, MessageAttribute {
public static func messageTag(reaction: MessageReaction.Reaction) -> MemoryBuffer {
let buffer = WriteBuffer()
var prefix: UInt8 = 0
buffer.write(&prefix, offset: 0, length: 1)
switch reaction {
case let .builtin(value):
var stringData = value.data(using: .utf8) ?? Data()
var length: UInt8 = UInt8(clamping: stringData.count)
if stringData.count > Int(length) {
stringData.count = Int(length)
}
var typeId: UInt8 = 0
buffer.write(&typeId, offset: 0, length: 1)
buffer.write(&length, offset: 0, length: 1)
buffer.write(stringData)
case var .custom(fileId):
var typeId: UInt8 = 1
buffer.write(&typeId, offset: 0, length: 1)
buffer.write(&fileId, offset: 0, length: 8)
case .stars:
var typeId: UInt8 = 2
buffer.write(&typeId, offset: 0, length: 1)
}
return buffer
}
public static func reactionFromMessageTag(tag: MemoryBuffer) -> MessageReaction.Reaction? {
if tag.length < 2 {
return nil
}
let readBuffer = ReadBuffer(memoryBufferNoCopy: tag)
var prefix: UInt8 = 0
readBuffer.read(&prefix, offset: 0, length: 1)
if prefix != 0 {
return nil
}
var typeId: UInt8 = 0
readBuffer.read(&typeId, offset: 0, length: 1)
switch typeId {
case 0:
var length8: UInt8 = 0
readBuffer.read(&length8, offset: 0, length: 1)
let length = Int(length8)
if readBuffer.offset + length > readBuffer.length {
return nil
}
let data = readBuffer.readData(length: length)
guard let string = String(data: data, encoding: .utf8) else {
return nil
}
return .builtin(string)
case 1:
if readBuffer.offset + 8 > readBuffer.length {
return nil
}
var fileId: Int64 = 0
readBuffer.read(&fileId, offset: 0, length: 8)
return .custom(fileId)
case 2:
return .stars
default:
return nil
}
}
public struct RecentPeer: Equatable, PostboxCoding {
public var value: MessageReaction.Reaction
public var isLarge: Bool
public var isUnseen: Bool
public var isMy: Bool
public var peerId: PeerId
public var timestamp: Int32?
public init(value: MessageReaction.Reaction, isLarge: Bool, isUnseen: Bool, isMy: Bool, peerId: PeerId, timestamp: Int32?) {
self.value = value
self.isLarge = isLarge
self.isUnseen = isUnseen
self.isMy = isMy
self.peerId = peerId
self.timestamp = timestamp
}
public init(decoder: PostboxDecoder) {
if let value = decoder.decodeOptionalStringForKey("v") {
self.value = .builtin(value)
} else if let _ = decoder.decodeOptionalInt64ForKey("star") {
self.value = .stars
} else {
self.value = .custom(decoder.decodeInt64ForKey("cfid", orElse: 0))
}
self.isLarge = decoder.decodeInt32ForKey("l", orElse: 0) != 0
self.isUnseen = decoder.decodeInt32ForKey("u", orElse: 0) != 0
self.isMy = decoder.decodeInt32ForKey("my", orElse: 0) != 0
self.peerId = PeerId(decoder.decodeInt64ForKey("p", orElse: 0))
self.timestamp = decoder.decodeOptionalInt32ForKey("ts")
}
public func encode(_ encoder: PostboxEncoder) {
switch self.value {
case let .builtin(value):
encoder.encodeString(value, forKey: "v")
case let .custom(fileId):
encoder.encodeInt64(fileId, forKey: "cfid")
case .stars:
encoder.encodeInt64(0, forKey: "star")
}
encoder.encodeInt32(self.isLarge ? 1 : 0, forKey: "l")
encoder.encodeInt32(self.isUnseen ? 1 : 0, forKey: "u")
encoder.encodeInt32(self.isMy ? 1 : 0, forKey: "my")
encoder.encodeInt64(self.peerId.toInt64(), forKey: "p")
if let timestamp = self.timestamp {
encoder.encodeInt32(timestamp, forKey: "ts")
} else {
encoder.encodeNil(forKey: "ts")
}
}
}
public struct TopPeer: Equatable, PostboxCoding {
public var peerId: PeerId?
public var count: Int32
public var isTop: Bool
public var isMy: Bool
public var isAnonymous: Bool
public init(peerId: PeerId?, count: Int32, isTop: Bool, isMy: Bool, isAnonymous: Bool) {
self.peerId = peerId
self.count = count
self.isMy = isMy
self.isTop = isTop
self.isAnonymous = isAnonymous
}
public init(decoder: PostboxDecoder) {
if let peerId = decoder.decodeOptionalInt64ForKey("p") {
self.peerId = PeerId(peerId)
} else {
self.peerId = nil
}
self.count = decoder.decodeInt32ForKey("c", orElse: 0)
self.isTop = decoder.decodeBoolForKey("t", orElse: false)
self.isMy = decoder.decodeBoolForKey("m", orElse: false)
self.isAnonymous = decoder.decodeBoolForKey("anon", orElse: false)
}
public func encode(_ encoder: PostboxEncoder) {
if let peerId = self.peerId {
encoder.encodeInt64(peerId.toInt64(), forKey: "p")
} else {
encoder.encodeNil(forKey: "p")
}
encoder.encodeInt32(self.count, forKey: "c")
encoder.encodeBool(self.isTop, forKey: "t")
encoder.encodeBool(self.isMy, forKey: "m")
encoder.encodeBool(self.isAnonymous, forKey: "anon")
}
}
public let canViewList: Bool
public let isTags: Bool
public let reactions: [MessageReaction]
public let recentPeers: [RecentPeer]
public let topPeers: [TopPeer]
public var associatedPeerIds: [PeerId] {
return self.recentPeers.map(\.peerId)
}
public var associatedMediaIds: [MediaId] {
var result: [MediaId] = []
for reaction in self.reactions {
switch reaction.value {
case .builtin:
break
case let .custom(fileId):
let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId)
if !result.contains(mediaId) {
result.append(mediaId)
}
case .stars:
break
}
}
return result
}
public init(canViewList: Bool, isTags: Bool, reactions: [MessageReaction], recentPeers: [RecentPeer], topPeers: [TopPeer]) {
self.canViewList = canViewList
self.isTags = isTags
self.reactions = reactions
self.recentPeers = recentPeers
self.topPeers = topPeers
}
required public init(decoder: PostboxDecoder) {
self.canViewList = decoder.decodeBoolForKey("vl", orElse: true)
self.isTags = decoder.decodeBoolForKey("tg", orElse: false)
self.reactions = decoder.decodeObjectArrayWithDecoderForKey("r")
self.recentPeers = decoder.decodeObjectArrayWithDecoderForKey("rp")
self.topPeers = decoder.decodeObjectArrayWithDecoderForKey("tp")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeBool(self.canViewList, forKey: "vl")
encoder.encodeBool(self.isTags, forKey: "tg")
encoder.encodeObjectArray(self.reactions, forKey: "r")
encoder.encodeObjectArray(self.recentPeers, forKey: "rp")
encoder.encodeObjectArray(self.topPeers, forKey: "tp")
}
public static func ==(lhs: ReactionsMessageAttribute, rhs: ReactionsMessageAttribute) -> Bool {
if lhs.canViewList != rhs.canViewList {
return false
}
if lhs.isTags != rhs.isTags {
return false
}
if lhs.reactions != rhs.reactions {
return false
}
if lhs.recentPeers != rhs.recentPeers {
return false
}
if lhs.topPeers != rhs.topPeers {
return false
}
return true
}
public var hasUnseen: Bool {
for recentPeer in self.recentPeers {
if recentPeer.isUnseen {
return true
}
}
return false
}
public func withAllSeen() -> ReactionsMessageAttribute {
return ReactionsMessageAttribute(
canViewList: self.canViewList,
isTags: self.isTags,
reactions: self.reactions,
recentPeers: self.recentPeers.map { recentPeer in
var recentPeer = recentPeer
recentPeer.isUnseen = false
return recentPeer
},
topPeers: self.topPeers
)
}
}
public final class PendingReactionsMessageAttribute: MessageAttribute {
public struct PendingReaction: Equatable, PostboxCoding {
public var value: MessageReaction.Reaction
public var sendAsPeerId: PeerId?
public init(value: MessageReaction.Reaction, sendAsPeerId: PeerId?) {
self.value = value
self.sendAsPeerId = sendAsPeerId
}
public init(decoder: PostboxDecoder) {
self.value = decoder.decodeObjectForKey("val", decoder: { MessageReaction.Reaction(decoder: $0) }) as! MessageReaction.Reaction
self.sendAsPeerId = decoder.decodeOptionalInt64ForKey("sa").flatMap(PeerId.init)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObject(self.value, forKey: "val")
if let sendAsPeerId = self.sendAsPeerId {
encoder.encodeInt64(sendAsPeerId.toInt64(), forKey: "sa")
} else {
encoder.encodeNil(forKey: "sa")
}
}
}
public let accountPeerId: PeerId?
public let reactions: [PendingReaction]
public let isLarge: Bool
public let storeAsRecentlyUsed: Bool
public let isTags: Bool
public var associatedPeerIds: [PeerId] {
var peerIds: [PeerId] = []
if let accountPeerId = self.accountPeerId {
peerIds.append(accountPeerId)
}
for reaction in self.reactions {
if let sendAsPeerId = reaction.sendAsPeerId {
if !peerIds.contains(sendAsPeerId) {
peerIds.append(sendAsPeerId)
}
}
}
return peerIds
}
public var associatedMediaIds: [MediaId] {
var result: [MediaId] = []
for reaction in self.reactions {
switch reaction.value {
case .builtin:
break
case let .custom(fileId):
let mediaId = MediaId(namespace: Namespaces.Media.CloudFile, id: fileId)
if !result.contains(mediaId) {
result.append(mediaId)
}
case .stars:
break
}
}
return result
}
public init(accountPeerId: PeerId?, reactions: [PendingReaction], isLarge: Bool, storeAsRecentlyUsed: Bool, isTags: Bool) {
self.accountPeerId = accountPeerId
self.reactions = reactions
self.isLarge = isLarge
self.storeAsRecentlyUsed = storeAsRecentlyUsed
self.isTags = isTags
}
required public init(decoder: PostboxDecoder) {
self.accountPeerId = decoder.decodeOptionalInt64ForKey("ap").flatMap(PeerId.init)
self.reactions = decoder.decodeObjectArrayWithDecoderForKey("reac")
self.isLarge = decoder.decodeInt32ForKey("l", orElse: 0) != 0
self.storeAsRecentlyUsed = decoder.decodeInt32ForKey("used", orElse: 0) != 0
self.isTags = decoder.decodeBoolForKey("itag", orElse: false)
}
public func encode(_ encoder: PostboxEncoder) {
if let accountPeerId = self.accountPeerId {
encoder.encodeInt64(accountPeerId.toInt64(), forKey: "ap")
} else {
encoder.encodeNil(forKey: "ap")
}
encoder.encodeObjectArray(self.reactions, forKey: "reac")
encoder.encodeInt32(self.isLarge ? 1 : 0, forKey: "l")
encoder.encodeInt32(self.storeAsRecentlyUsed ? 1 : 0, forKey: "used")
encoder.encodeBool(self.isTags, forKey: "itag")
}
}
public final class PendingStarsReactionsMessageAttribute: MessageAttribute {
public let accountPeerId: PeerId?
public let count: Int32
public let privacy: TelegramPaidReactionPrivacy
public var associatedPeerIds: [PeerId] {
var peerIds: [PeerId] = []
if let accountPeerId = self.accountPeerId {
peerIds.append(accountPeerId)
}
return peerIds
}
public init(accountPeerId: PeerId?, count: Int32, privacy: TelegramPaidReactionPrivacy) {
self.accountPeerId = accountPeerId
self.count = count
self.privacy = privacy
}
required public init(decoder: PostboxDecoder) {
self.accountPeerId = decoder.decodeOptionalInt64ForKey("ap").flatMap(PeerId.init)
self.count = decoder.decodeInt32ForKey("cnt", orElse: 1)
if let privacy = decoder.decode(TelegramPaidReactionPrivacy.self, forKey: "priv") {
self.privacy = privacy
} else {
self.privacy = decoder.decodeBoolForKey("anon", orElse: false) ? .anonymous : .default
}
}
public func encode(_ encoder: PostboxEncoder) {
if let accountPeerId = self.accountPeerId {
encoder.encodeInt64(accountPeerId.toInt64(), forKey: "ap")
} else {
encoder.encodeNil(forKey: "ap")
}
encoder.encodeInt32(self.count, forKey: "cnt")
encoder.encode(self.privacy, forKey: "priv")
}
}
@@ -0,0 +1,259 @@
import Foundation
import Postbox
import SwiftSignalKit
public final class RecentDownloadItem: Codable, Equatable {
struct Id {
var rawValue: MemoryBuffer
init(id: MessageId, resourceId: String) {
let buffer = WriteBuffer()
var idId: Int32 = id.id
buffer.write(&idId, length: 4)
var idNamespace: Int32 = id.namespace
buffer.write(&idNamespace, length: 4)
var peerId: Int64 = id.peerId.toInt64()
buffer.write(&peerId, length: 8)
let resourceIdData = resourceId.data(using: .utf8)!
var resourceIdLength = Int32(resourceIdData.count)
buffer.write(&resourceIdLength, length: 4)
buffer.write(resourceIdData)
self.rawValue = buffer.makeReadBufferAndReset()
}
}
public let messageId: MessageId
public let resourceId: String
public let timestamp: Int32
public let isSeen: Bool
public init(messageId: MessageId, resourceId: String, timestamp: Int32, isSeen: Bool) {
self.messageId = messageId
self.resourceId = resourceId
self.timestamp = timestamp
self.isSeen = isSeen
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.messageId = try container.decode(MessageId.self, forKey: "messageId")
self.resourceId = try container.decode(String.self, forKey: "resourceId")
self.timestamp = try container.decode(Int32.self, forKey: "timestamp")
self.isSeen = try container.decodeIfPresent(Bool.self, forKey: "isSeen") ?? false
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.messageId, forKey: "messageId")
try container.encode(self.resourceId, forKey: "resourceId")
try container.encode(self.timestamp, forKey: "timestamp")
try container.encode(self.isSeen, forKey: "isSeen")
}
public static func ==(lhs: RecentDownloadItem, rhs: RecentDownloadItem) -> Bool {
if lhs.messageId != rhs.messageId {
return false
}
if lhs.resourceId != rhs.resourceId {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
if lhs.isSeen != rhs.isSeen {
return false
}
return true
}
func withSeen() -> RecentDownloadItem {
return RecentDownloadItem(messageId: self.messageId, resourceId: self.resourceId, timestamp: self.timestamp, isSeen: true)
}
}
public final class RenderedRecentDownloadItem: Equatable {
public let message: Message
public let timestamp: Int32
public let isSeen: Bool
public let resourceId: String
public let size: Int64
public init(message: Message, timestamp: Int32, isSeen: Bool, resourceId: String, size: Int64) {
self.message = message
self.timestamp = timestamp
self.isSeen = isSeen
self.resourceId = resourceId
self.size = size
}
public static func ==(lhs: RenderedRecentDownloadItem, rhs: RenderedRecentDownloadItem) -> Bool {
if lhs.message.id != rhs.message.id {
return false
}
if lhs.message.stableVersion != rhs.message.stableVersion {
return false
}
if lhs.timestamp != rhs.timestamp {
return false
}
if lhs.isSeen != rhs.isSeen {
return false
}
if lhs.resourceId != rhs.resourceId {
return false
}
if lhs.size != rhs.size {
return false
}
return true
}
}
public func recentDownloadItems(postbox: Postbox) -> Signal<[RenderedRecentDownloadItem], NoError> {
let viewKey: PostboxViewKey = .orderedItemList(id: Namespaces.OrderedItemList.RecentDownloads)
return postbox.combinedView(keys: [viewKey])
|> mapToSignal { views -> Signal<[RenderedRecentDownloadItem], NoError> in
guard let view = views.views[viewKey] as? OrderedItemListView else {
return .single([])
}
return combineLatest(postbox.transaction { transaction -> [RenderedRecentDownloadItem] in
var result: [RenderedRecentDownloadItem] = []
for item in view.items {
guard let item = item.contents.get(RecentDownloadItem.self) else {
continue
}
guard let message = transaction.getMessage(item.messageId) else {
continue
}
var size: Int64?
for media in message.media {
if let result = findMediaResourceById(media: media, resourceId: MediaResourceId(item.resourceId)) {
size = result.size
break
}
}
if let size = size {
result.append(RenderedRecentDownloadItem(message: message, timestamp: item.timestamp, isSeen: item.isSeen, resourceId: item.resourceId, size: size))
}
}
return result
}, postbox.mediaBox.didRemoveResources)
|> mapToSignal { items, _ -> Signal<[RenderedRecentDownloadItem], NoError> in
var statusSignals: [Signal<Bool, NoError>] = []
for item in items {
statusSignals.append(postbox.mediaBox.resourceStatus(MediaResourceId(item.resourceId), resourceSize: item.size)
|> map { status -> Bool in
switch status {
case .Local:
return true
default:
return false
}
}
|> distinctUntilChanged)
}
return combineLatest(queue: .mainQueue(), statusSignals)
|> map { statuses -> [RenderedRecentDownloadItem] in
var result: [RenderedRecentDownloadItem] = []
for i in 0 ..< items.count {
if statuses[i] {
result.append(items[i])
}
}
return result
}
}
}
}
public func addRecentDownloadItem(postbox: Postbox, item: RecentDownloadItem) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
guard let entry = CodableEntry(item) else {
return
}
transaction.addOrMoveToFirstPositionOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentDownloads, item: OrderedItemListEntry(id: RecentDownloadItem.Id(id: item.messageId, resourceId: item.resourceId).rawValue, contents: entry), removeTailIfCountExceeds: 200)
}
|> ignoreValues
}
public func clearRecentDownloadList(postbox: Postbox) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.RecentDownloads, items: [])
}
|> ignoreValues
}
public func markRecentDownloadItemsAsSeen(postbox: Postbox, items: [(messageId: MessageId, resourceId: String)]) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
var unseenIds: [(messageId: MessageId, resourceId: String)] = []
for item in items {
guard let listItem = transaction.getOrderedItemListItem(collectionId: Namespaces.OrderedItemList.RecentDownloads, itemId: RecentDownloadItem.Id(id: item.messageId, resourceId: item.resourceId).rawValue) else {
continue
}
guard let listItemValue = listItem.contents.get(RecentDownloadItem.self), !listItemValue.isSeen else {
continue
}
unseenIds.append(item)
}
if unseenIds.isEmpty {
return
}
let items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.RecentDownloads)
transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.RecentDownloads, items: items.compactMap { entry -> OrderedItemListEntry? in
guard let item = entry.contents.get(RecentDownloadItem.self) else {
return nil
}
if unseenIds.contains(where: { $0.messageId == item.messageId && $0.resourceId == item.resourceId }) {
guard let entry = CodableEntry(item.withSeen()) else {
return nil
}
return OrderedItemListEntry(id: RecentDownloadItem.Id(id: item.messageId, resourceId: item.resourceId).rawValue, contents: entry)
} else {
return entry
}
})
}
|> ignoreValues
}
public func markAllRecentDownloadItemsAsSeen(postbox: Postbox) -> Signal<Never, NoError> {
return postbox.transaction { transaction -> Void in
let items = transaction.getOrderedListItems(collectionId: Namespaces.OrderedItemList.RecentDownloads)
var hasUnseen = false
for item in items {
if let item = item.contents.get(RecentDownloadItem.self), !item.isSeen {
hasUnseen = true
break
}
}
if !hasUnseen {
return
}
transaction.replaceOrderedItemListItems(collectionId: Namespaces.OrderedItemList.RecentDownloads, items: items.compactMap { item -> OrderedItemListEntry? in
guard let item = item.contents.get(RecentDownloadItem.self) else {
return nil
}
guard let entry = CodableEntry(item.withSeen()) else {
return nil
}
return OrderedItemListEntry(id: RecentDownloadItem.Id(id: item.messageId, resourceId: item.resourceId).rawValue, contents: entry)
})
}
|> ignoreValues
}
@@ -0,0 +1,12 @@
import Postbox
public final class RecentHashtagItem: Codable {
public init() {
}
public init(from decoder: Decoder) throws {
}
public func encode(to encoder: Encoder) throws {
}
}
@@ -0,0 +1,366 @@
import Foundation
import Postbox
import FlatBuffers
import FlatSerialization
public struct RecentMediaItemId {
public let rawValue: MemoryBuffer
public let mediaId: MediaId
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length == 4 + 8)
var mediaIdNamespace: Int32 = 0
var mediaIdId: Int64 = 0
memcpy(&mediaIdNamespace, rawValue.memory, 4)
memcpy(&mediaIdId, rawValue.memory.advanced(by: 4), 8)
self.mediaId = MediaId(namespace: mediaIdNamespace, id: mediaIdId)
}
public init(_ mediaId: MediaId) {
self.mediaId = mediaId
var mediaIdNamespace: Int32 = mediaId.namespace
var mediaIdId: Int64 = mediaId.id
self.rawValue = MemoryBuffer(memory: malloc(4 + 8)!, capacity: 4 + 8, length: 4 + 8, freeWhenDone: true)
memcpy(self.rawValue.memory, &mediaIdNamespace, 4)
memcpy(self.rawValue.memory.advanced(by: 4), &mediaIdId, 8)
}
}
public final class RecentMediaItem: Codable, Equatable {
public let media: TelegramMediaFile.Accessor
private let serializedFile: Data?
public init(_ media: TelegramMediaFile) {
self.media = TelegramMediaFile.Accessor(media)
self.serializedFile = nil
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let serializedFileData = try container.decodeIfPresent(Data.self, forKey: "md") {
self.serializedFile = serializedFileData
var byteBuffer = ByteBuffer(data: serializedFileData)
self.media = TelegramMediaFile.Accessor(FlatBuffers_getRoot(byteBuffer: &byteBuffer) as TelegramCore_TelegramMediaFile, serializedFileData)
} else {
let mediaData = try container.decode(AdaptedPostboxDecoder.RawObjectData.self, forKey: "m")
let media = TelegramMediaFile(decoder: PostboxDecoder(buffer: MemoryBuffer(data: mediaData.data)))
self.media = TelegramMediaFile.Accessor(media)
self.serializedFile = nil
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
if let serializedFile = self.serializedFile {
try container.encode(serializedFile, forKey: "md")
} else if let file = self.media._wrappedFile {
var builder = FlatBufferBuilder(initialSize: 1024)
let value = file.encodeToFlatBuffers(builder: &builder)
builder.finish(offset: value)
let serializedFile = builder.data
try container.encode(serializedFile, forKey: "md")
} else {
preconditionFailure()
}
}
public static func ==(lhs: RecentMediaItem, rhs: RecentMediaItem) -> Bool {
return lhs.media == rhs.media
}
}
public struct RecentEmojiItemId {
public enum Id {
case media(MediaId)
case text(String)
}
public let rawValue: MemoryBuffer
public let id: Id
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length >= 1)
var type: UInt8 = 0
memcpy(&type, rawValue.memory.advanced(by: 0), 1)
if type == 0 {
assert(rawValue.length == 1 + 4 + 8)
var mediaIdNamespace: Int32 = 0
var mediaIdId: Int64 = 0
memcpy(&mediaIdNamespace, rawValue.memory.advanced(by: 1), 4)
memcpy(&mediaIdId, rawValue.memory.advanced(by: 1 + 4), 8)
self.id = .media(MediaId(namespace: mediaIdNamespace, id: mediaIdId))
} else if type == 1 {
var length: UInt16 = 0
assert(rawValue.length >= 1 + 2)
memcpy(&length, rawValue.memory.advanced(by: 1), 2)
assert(rawValue.length >= 1 + 2 + Int(length))
self.id = .text(String(data: Data(bytes: rawValue.memory.advanced(by: 1 + 2), count: Int(length)), encoding: .utf8) ?? ".")
} else {
assert(false)
self.id = .text(".")
}
}
public init(_ mediaId: MediaId) {
self.id = .media(mediaId)
var mediaIdNamespace: Int32 = mediaId.namespace
var mediaIdId: Int64 = mediaId.id
self.rawValue = MemoryBuffer(memory: malloc(1 + 4 + 8)!, capacity: 1 + 4 + 8, length: 1 + 4 + 8, freeWhenDone: true)
var type: UInt8 = 0
memcpy(self.rawValue.memory.advanced(by: 0), &type, 1)
memcpy(self.rawValue.memory.advanced(by: 1), &mediaIdNamespace, 4)
memcpy(self.rawValue.memory.advanced(by: 1 + 4), &mediaIdId, 8)
}
public init(_ text: String) {
self.id = .text(text)
let data = text.data(using: .utf8) ?? Data()
var length: UInt16 = UInt16(data.count)
self.rawValue = MemoryBuffer(memory: malloc(1 + 2 + data.count)!, capacity: 1 + 2 + data.count, length: 1 + 2 + data.count, freeWhenDone: true)
var type: UInt8 = 1
memcpy(self.rawValue.memory.advanced(by: 0), &type, 1)
memcpy(self.rawValue.memory.advanced(by: 1), &length, 2)
data.withUnsafeBytes { bytes in
let _ = memcpy(self.rawValue.memory.advanced(by: 1 + 2), bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), bytes.count)
}
}
}
public final class RecentEmojiItem: Codable, Equatable {
public enum Content: Equatable {
case file(TelegramMediaFile)
case text(String)
}
public let content: Content
public init(_ content: Content) {
self.content = content
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let mediaData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "m") {
self.content = .file(TelegramMediaFile(decoder: PostboxDecoder(buffer: MemoryBuffer(data: mediaData.data))))
} else {
self.content = .text(try container.decode(String.self, forKey: "s"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self.content {
case let .file(file):
try container.encode(PostboxEncoder().encodeObjectToRawData(file), forKey: "m")
case let .text(string):
try container.encode(string, forKey: "s")
}
}
public static func ==(lhs: RecentEmojiItem, rhs: RecentEmojiItem) -> Bool {
return lhs.content == rhs.content
}
}
public struct RecentReactionItemId {
public enum Id: Hashable {
case custom(MediaId)
case builtin(String)
case stars
}
public let rawValue: MemoryBuffer
public let id: Id
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length >= 1)
var type: UInt8 = 0
memcpy(&type, rawValue.memory.advanced(by: 0), 1)
if type == 0 {
assert(rawValue.length == 1 + 4 + 8)
var mediaIdNamespace: Int32 = 0
var mediaIdId: Int64 = 0
memcpy(&mediaIdNamespace, rawValue.memory.advanced(by: 1), 4)
memcpy(&mediaIdId, rawValue.memory.advanced(by: 1 + 4), 8)
self.id = .custom(MediaId(namespace: mediaIdNamespace, id: mediaIdId))
} else if type == 1 {
var length: UInt16 = 0
assert(rawValue.length >= 1 + 2)
memcpy(&length, rawValue.memory.advanced(by: 1), 2)
assert(rawValue.length >= 1 + 2 + Int(length))
self.id = .builtin(String(data: Data(bytes: rawValue.memory.advanced(by: 1 + 2), count: Int(length)), encoding: .utf8) ?? ".")
} else if type == 2 {
self.id = .stars
} else {
assert(false)
self.id = .builtin(".")
}
}
public init(_ mediaId: MediaId) {
self.id = .custom(mediaId)
var mediaIdNamespace: Int32 = mediaId.namespace
var mediaIdId: Int64 = mediaId.id
self.rawValue = MemoryBuffer(memory: malloc(1 + 4 + 8)!, capacity: 1 + 4 + 8, length: 1 + 4 + 8, freeWhenDone: true)
var type: UInt8 = 0
memcpy(self.rawValue.memory.advanced(by: 0), &type, 1)
memcpy(self.rawValue.memory.advanced(by: 1), &mediaIdNamespace, 4)
memcpy(self.rawValue.memory.advanced(by: 1 + 4), &mediaIdId, 8)
}
public init(_ text: String) {
self.id = .builtin(text)
let data = text.data(using: .utf8) ?? Data()
var length: UInt16 = UInt16(data.count)
self.rawValue = MemoryBuffer(memory: malloc(1 + 2 + data.count)!, capacity: 1 + 2 + data.count, length: 1 + 2 + data.count, freeWhenDone: true)
var type: UInt8 = 1
memcpy(self.rawValue.memory.advanced(by: 0), &type, 1)
memcpy(self.rawValue.memory.advanced(by: 1), &length, 2)
data.withUnsafeBytes { bytes in
let _ = memcpy(self.rawValue.memory.advanced(by: 1 + 2), bytes.baseAddress!.assumingMemoryBound(to: UInt8.self), bytes.count)
}
}
public init(_ id: Id) {
precondition(id == .stars)
self.id = id
self.rawValue = MemoryBuffer(memory: malloc(1)!, capacity: 1, length: 1, freeWhenDone: true)
var type: UInt8 = 2
memcpy(self.rawValue.memory.advanced(by: 0), &type, 1)
}
}
public final class RecentReactionItem: Codable, Equatable {
public enum Content: Equatable {
case custom(TelegramMediaFile.Accessor)
case builtin(String)
case stars
}
public let content: Content
public var id: RecentReactionItemId {
switch self.content {
case let .builtin(value):
return RecentReactionItemId(value)
case let .custom(file):
return RecentReactionItemId(file.fileId)
case .stars:
return RecentReactionItemId(.stars)
}
}
public init(_ content: Content) {
self.content = content
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
if let mediaData = try container.decodeIfPresent(Data.self, forKey: "md") {
var byteBuffer = ByteBuffer(data: mediaData)
let file = TelegramMediaFile.Accessor(FlatBuffers_getRoot(byteBuffer: &byteBuffer) as TelegramCore_TelegramMediaFile, mediaData)
self.content = .custom(file)
} else if let mediaData = try container.decodeIfPresent(AdaptedPostboxDecoder.RawObjectData.self, forKey: "m") {
self.content = .custom(TelegramMediaFile.Accessor(TelegramMediaFile(decoder: PostboxDecoder(buffer: MemoryBuffer(data: mediaData.data)))))
} else if let _ = try container.decodeIfPresent(Int64.self, forKey: "star") {
self.content = .stars
} else {
self.content = .builtin(try container.decode(String.self, forKey: "s"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
switch self.content {
case let .custom(file):
if let serializedFile = file._wrappedData {
try container.encode(serializedFile, forKey: "md")
} else if let file = file._wrappedFile {
var builder = FlatBufferBuilder(initialSize: 1024)
let value = file.encodeToFlatBuffers(builder: &builder)
builder.finish(offset: value)
let serializedFile = builder.data
try container.encode(serializedFile, forKey: "md")
} else {
preconditionFailure()
}
case let .builtin(string):
try container.encode(string, forKey: "s")
case .stars:
try container.encode(0 as Int64, forKey: "star")
}
}
public static func ==(lhs: RecentReactionItem, rhs: RecentReactionItem) -> Bool {
return lhs.content == rhs.content
}
}
public struct RecentStarGiftItemId {
public let rawValue: MemoryBuffer
public let id: Int64
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length == 8)
var id: Int64 = 0
memcpy(&id, rawValue.memory, 8)
self.id = id
}
public init(_ id: Int64) {
var id = id
self.id = id
self.rawValue = MemoryBuffer(memory: malloc(8)!, capacity: 8, length: 8, freeWhenDone: true)
memcpy(self.rawValue.memory, &id, 8)
}
}
public final class RecentStarGiftItem: Codable, Equatable {
public let starGift: StarGift.UniqueGift
public init(_ starGift: StarGift.UniqueGift) {
self.starGift = starGift
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.starGift = try container.decode(StarGift.UniqueGift.self, forKey: "g")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.starGift, forKey: "g")
}
public static func ==(lhs: RecentStarGiftItem, rhs: RecentStarGiftItem) -> Bool {
return lhs.starGift == rhs.starGift
}
}
@@ -0,0 +1,42 @@
import Foundation
import Postbox
public struct RecentPeerItemId {
public let rawValue: MemoryBuffer
public let peerId: PeerId
public init(_ rawValue: MemoryBuffer) {
self.rawValue = rawValue
assert(rawValue.length == 8)
var idValue: Int64 = 0
memcpy(&idValue, rawValue.memory, 8)
self.peerId = PeerId(idValue)
}
public init(_ peerId: PeerId) {
self.peerId = peerId
var idValue: Int64 = peerId.toInt64()
self.rawValue = MemoryBuffer(memory: malloc(8)!, capacity: 8, length: 8, freeWhenDone: true)
memcpy(self.rawValue.memory, &idValue, 8)
}
}
public final class RecentPeerItem: Codable {
public let rating: Double
public init(rating: Double) {
self.rating = rating
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.rating = try container.decode(Double.self, forKey: "r")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.rating, forKey: "r")
}
}
@@ -0,0 +1,36 @@
import Postbox
public final class RegularChatState: PeerChatState, Equatable {
public let invalidatedPts: Int32?
public init(invalidatedPts: Int32?) {
self.invalidatedPts = invalidatedPts
}
public init(decoder: PostboxDecoder) {
self.invalidatedPts = decoder.decodeOptionalInt32ForKey("ipts")
}
public func encode(_ encoder: PostboxEncoder) {
if let invalidatedPts = self.invalidatedPts {
encoder.encodeInt32(invalidatedPts, forKey: "ipts")
} else {
encoder.encodeNil(forKey: "ipts")
}
}
public func withUpdatedInvalidatedPts(_ invalidatedPts: Int32?) -> RegularChatState {
return RegularChatState(invalidatedPts: invalidatedPts)
}
public func equals(_ other: PeerChatState) -> Bool {
if let other = other as? RegularChatState, other == self {
return true
}
return false
}
public static func ==(lhs: RegularChatState, rhs: RegularChatState) -> Bool {
return lhs.invalidatedPts == rhs.invalidatedPts
}
}
@@ -0,0 +1,28 @@
import Postbox
public final class RemoteStorageConfiguration: Codable, Equatable {
public let webDocumentsHostDatacenterId: Int32
public init(webDocumentsHostDatacenterId: Int32) {
self.webDocumentsHostDatacenterId = webDocumentsHostDatacenterId
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
self.webDocumentsHostDatacenterId = try container.decode(Int32.self, forKey: "webDocumentsHostDatacenterId")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(self.webDocumentsHostDatacenterId, forKey: "webDocumentsHostDatacenterId")
}
public static func ==(lhs: RemoteStorageConfiguration, rhs: RemoteStorageConfiguration) -> Bool {
if lhs.webDocumentsHostDatacenterId != rhs.webDocumentsHostDatacenterId {
return false
}
return true
}
}
@@ -0,0 +1,427 @@
import Postbox
public enum ReplyMarkupButtonRequestPeerType: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case discriminator = "d"
case user = "u"
case group = "g"
case channel = "c"
}
enum Discriminator: Int32 {
case user = 0
case group = 1
case channel = 2
}
public struct User: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case isBot = "b"
case isPremium = "p"
}
public var isBot: Bool?
public var isPremium: Bool?
public init(isBot: Bool?, isPremium: Bool?) {
self.isBot = isBot
self.isPremium = isPremium
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.isBot = try container.decodeIfPresent(Bool.self, forKey: .isBot)
self.isPremium = try container.decodeIfPresent(Bool.self, forKey: .isPremium)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.isBot, forKey: .isBot)
try container.encodeIfPresent(self.isPremium, forKey: .isPremium)
}
}
public struct Group: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case isCreator = "cr"
case hasUsername = "un"
case isForum = "fo"
case botParticipant = "bo"
case userAdminRights = "ur"
case botAdminRights = "br"
}
public var isCreator: Bool
public var hasUsername: Bool?
public var isForum: Bool?
public var botParticipant: Bool
public var userAdminRights: TelegramChatAdminRights?
public var botAdminRights: TelegramChatAdminRights?
public init(
isCreator: Bool,
hasUsername: Bool?,
isForum: Bool?,
botParticipant: Bool,
userAdminRights: TelegramChatAdminRights?,
botAdminRights: TelegramChatAdminRights?
) {
self.isCreator = isCreator
self.hasUsername = hasUsername
self.isForum = isForum
self.botParticipant = botParticipant
self.userAdminRights = userAdminRights
self.botAdminRights = botAdminRights
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.isCreator = try container.decode(Bool.self, forKey: .isCreator)
self.hasUsername = try container.decodeIfPresent(Bool.self, forKey: .hasUsername)
self.isForum = try container.decodeIfPresent(Bool.self, forKey: .isForum)
self.botParticipant = try container.decode(Bool.self, forKey: .botParticipant)
self.userAdminRights = try container.decodeIfPresent(TelegramChatAdminRights.self, forKey: .userAdminRights)
self.botAdminRights = try container.decodeIfPresent(TelegramChatAdminRights.self, forKey: .botAdminRights)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.isCreator, forKey: .isCreator)
try container.encodeIfPresent(self.hasUsername, forKey: .hasUsername)
try container.encodeIfPresent(self.isForum, forKey: .isForum)
try container.encode(self.botParticipant, forKey: .botParticipant)
try container.encodeIfPresent(self.userAdminRights, forKey: .userAdminRights)
try container.encodeIfPresent(self.botAdminRights, forKey: .botAdminRights)
}
}
public struct Channel: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case isCreator = "cr"
case hasUsername = "un"
case userAdminRights = "ur"
case botAdminRights = "br"
}
public var isCreator: Bool
public var hasUsername: Bool?
public var userAdminRights: TelegramChatAdminRights?
public var botAdminRights: TelegramChatAdminRights?
public init(
isCreator: Bool,
hasUsername: Bool?,
userAdminRights: TelegramChatAdminRights?,
botAdminRights: TelegramChatAdminRights?
) {
self.isCreator = isCreator
self.hasUsername = hasUsername
self.userAdminRights = userAdminRights
self.botAdminRights = botAdminRights
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.isCreator = try container.decode(Bool.self, forKey: .isCreator)
self.hasUsername = try container.decodeIfPresent(Bool.self, forKey: .hasUsername)
self.userAdminRights = try container.decodeIfPresent(TelegramChatAdminRights.self, forKey: .userAdminRights)
self.botAdminRights = try container.decodeIfPresent(TelegramChatAdminRights.self, forKey: .botAdminRights)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.isCreator, forKey: .isCreator)
try container.encodeIfPresent(self.hasUsername, forKey: .hasUsername)
try container.encodeIfPresent(self.userAdminRights, forKey: .userAdminRights)
try container.encodeIfPresent(self.botAdminRights, forKey: .botAdminRights)
}
}
case user(User)
case group(Group)
case channel(Channel)
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(Int32.self, forKey: .discriminator) {
case Discriminator.user.rawValue:
self = .user(try container.decode(User.self, forKey: .user))
case Discriminator.group.rawValue:
self = .group(try container.decode(Group.self, forKey: .group))
case Discriminator.channel.rawValue:
self = .channel(try container.decode(Channel.self, forKey: .channel))
default:
assertionFailure()
self = .user(User(isBot: nil, isPremium: nil))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .user(user):
try container.encode(Discriminator.user.rawValue, forKey: .discriminator)
try container.encode(user, forKey: .user)
case let .group(group):
try container.encode(Discriminator.group.rawValue, forKey: .discriminator)
try container.encode(group, forKey: .group)
case let .channel(channel):
try container.encode(Discriminator.channel.rawValue, forKey: .discriminator)
try container.encode(channel, forKey: .channel)
}
}
}
public enum ReplyMarkupButtonAction: PostboxCoding, Equatable {
public struct PeerTypes: OptionSet {
public var rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public init() {
self.rawValue = 0
}
public static let users = PeerTypes(rawValue: 1 << 0)
public static let bots = PeerTypes(rawValue: 1 << 1)
public static let channels = PeerTypes(rawValue: 1 << 2)
public static let groups = PeerTypes(rawValue: 1 << 3)
public var requestPeerTypes: [ReplyMarkupButtonRequestPeerType]? {
if self.isEmpty {
return nil
}
var types: [ReplyMarkupButtonRequestPeerType] = []
if self.contains(.users) {
types.append(.user(.init(isBot: false, isPremium: nil)))
}
if self.contains(.bots) {
types.append(.user(.init(isBot: true, isPremium: nil)))
}
if self.contains(.channels) {
types.append(.channel(.init(isCreator: false, hasUsername: nil, userAdminRights: nil, botAdminRights: nil)))
}
if self.contains(.groups) {
types.append(.group(.init(isCreator: false, hasUsername: nil, isForum: nil, botParticipant: false, userAdminRights: nil, botAdminRights: nil)))
}
return types
}
}
case text
case url(String)
case callback(requiresPassword: Bool, data: MemoryBuffer)
case requestPhone
case requestMap
case switchInline(samePeer: Bool, query: String, peerTypes: PeerTypes)
case openWebApp
case payment
case urlAuth(url: String, buttonId: Int32)
case setupPoll(isQuiz: Bool?)
case openUserProfile(peerId: PeerId)
case openWebView(url: String, simple: Bool)
case requestPeer(peerType: ReplyMarkupButtonRequestPeerType, buttonId: Int32, maxQuantity: Int32)
case copyText(payload: String)
public init(decoder: PostboxDecoder) {
switch decoder.decodeInt32ForKey("v", orElse: 0) {
case 0:
self = .text
case 1:
self = .url(decoder.decodeStringForKey("u", orElse: ""))
case 2:
self = .callback(requiresPassword: decoder.decodeInt32ForKey("p", orElse: 0) != 0, data: decoder.decodeBytesForKey("d") ?? MemoryBuffer())
case 3:
self = .requestPhone
case 4:
self = .requestMap
case 5:
self = .switchInline(samePeer: decoder.decodeInt32ForKey("s", orElse: 0) != 0, query: decoder.decodeStringForKey("q", orElse: ""), peerTypes: PeerTypes(rawValue: decoder.decodeInt32ForKey("pt", orElse: 0)))
case 6:
self = .openWebApp
case 7:
self = .payment
case 8:
self = .urlAuth(url: decoder.decodeStringForKey("u", orElse: ""), buttonId: decoder.decodeInt32ForKey("b", orElse: 0))
case 9:
self = .setupPoll(isQuiz: decoder.decodeOptionalInt32ForKey("isq").flatMap { $0 != 0 })
case 10:
self = .openUserProfile(peerId: PeerId(decoder.decodeInt64ForKey("peerId", orElse: 0)))
case 11:
self = .openWebView(url: decoder.decodeStringForKey("u", orElse: ""), simple: decoder.decodeInt32ForKey("s", orElse: 0) != 0)
case 12:
self = .requestPeer(peerType: decoder.decode(ReplyMarkupButtonRequestPeerType.self, forKey: "pt") ?? ReplyMarkupButtonRequestPeerType.user(ReplyMarkupButtonRequestPeerType.User(isBot: nil, isPremium: nil)), buttonId: decoder.decodeInt32ForKey("b", orElse: 0), maxQuantity: decoder.decodeInt32ForKey("q", orElse: 1))
case 13:
self = .copyText(payload: decoder.decodeStringForKey("p", orElse: ""))
default:
self = .text
}
}
public func encode(_ encoder: PostboxEncoder) {
switch self {
case .text:
encoder.encodeInt32(0, forKey: "v")
case let .url(url):
encoder.encodeInt32(1, forKey: "v")
encoder.encodeString(url, forKey: "u")
case let .callback(requiresPassword, data):
encoder.encodeInt32(2, forKey: "v")
encoder.encodeInt32(requiresPassword ? 1 : 0, forKey: "p")
encoder.encodeBytes(data, forKey: "d")
case .requestPhone:
encoder.encodeInt32(3, forKey: "v")
case .requestMap:
encoder.encodeInt32(4, forKey: "v")
case let .switchInline(samePeer, query, peerTypes):
encoder.encodeInt32(5, forKey: "v")
encoder.encodeInt32(samePeer ? 1 : 0, forKey: "s")
encoder.encodeString(query, forKey: "q")
encoder.encodeInt32(peerTypes.rawValue, forKey: "pt")
case .openWebApp:
encoder.encodeInt32(6, forKey: "v")
case .payment:
encoder.encodeInt32(7, forKey: "v")
case let .urlAuth(url, buttonId):
encoder.encodeInt32(8, forKey: "v")
encoder.encodeString(url, forKey: "u")
encoder.encodeInt32(buttonId, forKey: "b")
case let .setupPoll(isQuiz):
encoder.encodeInt32(9, forKey: "v")
if let isQuiz = isQuiz {
encoder.encodeInt32(isQuiz ? 1 : 0, forKey: "isq")
} else {
encoder.encodeNil(forKey: "isq")
}
case let .openUserProfile(peerId):
encoder.encodeInt32(10, forKey: "v")
encoder.encodeInt64(peerId.toInt64(), forKey: "peerId")
case let .openWebView(url, simple):
encoder.encodeInt32(11, forKey: "v")
encoder.encodeString(url, forKey: "u")
encoder.encodeInt32(simple ? 1 : 0, forKey: "s")
case let .requestPeer(peerType, buttonId, maxQuantity):
encoder.encodeInt32(12, forKey: "v")
encoder.encodeInt32(buttonId, forKey: "b")
encoder.encode(peerType, forKey: "pt")
encoder.encodeInt32(maxQuantity, forKey: "q")
case let .copyText(payload):
encoder.encodeInt32(13, forKey: "v")
encoder.encodeString(payload, forKey: "p")
}
}
}
public struct ReplyMarkupButton: PostboxCoding, Equatable {
public let title: String
public let titleWhenForwarded: String?
public let action: ReplyMarkupButtonAction
public init(title: String, titleWhenForwarded: String?, action: ReplyMarkupButtonAction) {
self.title = title
self.titleWhenForwarded = titleWhenForwarded
self.action = action
}
public init(decoder: PostboxDecoder) {
self.title = decoder.decodeStringForKey(".t", orElse: "")
self.titleWhenForwarded = decoder.decodeOptionalStringForKey(".tf")
self.action = ReplyMarkupButtonAction(decoder: decoder)
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeString(self.title, forKey: ".t")
if let titleWhenForwarded = self.titleWhenForwarded {
encoder.encodeString(titleWhenForwarded, forKey: ".tf")
} else {
encoder.encodeNil(forKey: ".tf")
}
self.action.encode(encoder)
}
public static func ==(lhs: ReplyMarkupButton, rhs: ReplyMarkupButton) -> Bool {
return lhs.title == rhs.title && lhs.action == rhs.action
}
}
public struct ReplyMarkupRow: PostboxCoding, Equatable {
public let buttons: [ReplyMarkupButton]
public init(buttons: [ReplyMarkupButton]) {
self.buttons = buttons
}
public init(decoder: PostboxDecoder) {
self.buttons = decoder.decodeObjectArrayWithDecoderForKey("b")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectArray(self.buttons, forKey: "b")
}
public static func ==(lhs: ReplyMarkupRow, rhs: ReplyMarkupRow) -> Bool {
return lhs.buttons == rhs.buttons
}
}
public struct ReplyMarkupMessageFlags: OptionSet {
public var rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
public init() {
self.rawValue = 0
}
public static let once = ReplyMarkupMessageFlags(rawValue: 1 << 0)
public static let personal = ReplyMarkupMessageFlags(rawValue: 1 << 1)
public static let setupReply = ReplyMarkupMessageFlags(rawValue: 1 << 2)
public static let inline = ReplyMarkupMessageFlags(rawValue: 1 << 3)
public static let fit = ReplyMarkupMessageFlags(rawValue: 1 << 4)
public static let persistent = ReplyMarkupMessageFlags(rawValue: 1 << 5)
}
public class ReplyMarkupMessageAttribute: MessageAttribute, Equatable {
public let rows: [ReplyMarkupRow]
public let flags: ReplyMarkupMessageFlags
public let placeholder: String?
public init(rows: [ReplyMarkupRow], flags: ReplyMarkupMessageFlags, placeholder: String?) {
self.rows = rows
self.flags = flags
self.placeholder = placeholder
}
public required init(decoder: PostboxDecoder) {
self.rows = decoder.decodeObjectArrayWithDecoderForKey("r")
self.flags = ReplyMarkupMessageFlags(rawValue: decoder.decodeInt32ForKey("f", orElse: 0))
self.placeholder = decoder.decodeOptionalStringForKey("pl")
}
public func encode(_ encoder: PostboxEncoder) {
encoder.encodeObjectArray(self.rows, forKey: "r")
encoder.encodeInt32(self.flags.rawValue, forKey: "f")
if let placeholder = self.placeholder {
encoder.encodeString(placeholder, forKey: "pl")
} else {
encoder.encodeNil(forKey: "pl")
}
}
public static func ==(lhs: ReplyMarkupMessageAttribute, rhs: ReplyMarkupMessageAttribute) -> Bool {
return lhs.flags == rhs.flags && lhs.rows == rhs.rows && lhs.placeholder == rhs.placeholder
}
}

Some files were not shown because too many files have changed in this diff Show More