mirror of
https://github.com/ichmagmaus111/ghostgram.git
synced 2026-07-24 16:30:50 +02:00
Update Ghostgram features
This commit is contained in:
+11
-7
@@ -50,7 +50,7 @@ func _internal_requestChangeAccountPhoneNumberVerification(account: Account, api
|
||||
appSandbox = pushNotificationConfiguration.isSandbox ? .boolTrue : .boolFalse
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.account.sendChangePhoneCode(phoneNumber: phoneNumber, settings: .codeSettings(flags: flags, logoutTokens: nil, token: token, appSandbox: appSandbox)), automaticFloodWait: false)
|
||||
return account.network.request(Api.functions.account.sendChangePhoneCode(phoneNumber: phoneNumber, settings: .codeSettings(.init(flags: flags, logoutTokens: nil, token: token, appSandbox: appSandbox))), automaticFloodWait: false)
|
||||
|> mapError { error -> RequestChangeAccountPhoneNumberVerificationError in
|
||||
if error.errorDescription.hasPrefix("FLOOD_WAIT") {
|
||||
return .limitExceeded
|
||||
@@ -66,13 +66,15 @@ func _internal_requestChangeAccountPhoneNumberVerification(account: Account, api
|
||||
}
|
||||
|> mapToSignal { sentCode -> Signal<ChangeAccountPhoneNumberData, RequestChangeAccountPhoneNumberVerificationError> in
|
||||
switch sentCode {
|
||||
case let .sentCode(_, type, phoneCodeHash, nextType, codeTimeout):
|
||||
case let .sentCode(sentCodeData):
|
||||
let (type, phoneCodeHash, nextType, codeTimeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout)
|
||||
var parsedNextType: AuthorizationCodeNextType?
|
||||
if let nextType = nextType {
|
||||
parsedNextType = AuthorizationCodeNextType(apiType: nextType)
|
||||
}
|
||||
|
||||
if case let .sentCodeTypeFirebaseSms(_, _, _, _, receipt, pushTimeout, _) = type {
|
||||
|
||||
if case let .sentCodeTypeFirebaseSms(sentCodeTypeFirebaseSmsData) = type {
|
||||
let (receipt, pushTimeout) = (sentCodeTypeFirebaseSmsData.receipt, sentCodeTypeFirebaseSmsData.pushTimeout)
|
||||
return firebaseSecretStream
|
||||
|> map { mapping -> String? in
|
||||
guard let receipt = receipt else {
|
||||
@@ -141,13 +143,15 @@ private func internalResendChangeAccountPhoneNumberVerification(account: Account
|
||||
}
|
||||
|> mapToSignal { sentCode -> Signal<ChangeAccountPhoneNumberData, RequestChangeAccountPhoneNumberVerificationError> in
|
||||
switch sentCode {
|
||||
case let .sentCode(_, type, phoneCodeHash, nextType, codeTimeout):
|
||||
case let .sentCode(sentCodeData):
|
||||
let (type, phoneCodeHash, nextType, codeTimeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout)
|
||||
var parsedNextType: AuthorizationCodeNextType?
|
||||
if let nextType = nextType {
|
||||
parsedNextType = AuthorizationCodeNextType(apiType: nextType)
|
||||
}
|
||||
|
||||
if case let .sentCodeTypeFirebaseSms(_, _, _, _, receipt, pushTimeout, _) = type {
|
||||
|
||||
if case let .sentCodeTypeFirebaseSms(sentCodeTypeFirebaseSmsData) = type {
|
||||
let (receipt, pushTimeout) = (sentCodeTypeFirebaseSmsData.receipt, sentCodeTypeFirebaseSmsData.pushTimeout)
|
||||
return firebaseSecretStream
|
||||
|> map { mapping -> String? in
|
||||
guard let receipt = receipt else {
|
||||
|
||||
+3
-3
@@ -90,7 +90,7 @@ public extension TelegramEngine {
|
||||
var textColor: Int32?
|
||||
for attribute in starGift.attributes {
|
||||
switch attribute {
|
||||
case let .model(_, fileValue, _):
|
||||
case let .model(_, fileValue, _, _):
|
||||
file = fileValue
|
||||
case let .pattern(_, patternFileValue, _):
|
||||
patternFile = patternFileValue
|
||||
@@ -106,7 +106,7 @@ public extension TelegramEngine {
|
||||
let apiEmojiStatus: Api.EmojiStatus
|
||||
var emojiStatus: PeerEmojiStatus?
|
||||
if let file, let patternFile, let innerColor, let outerColor, let patternColor, let textColor {
|
||||
apiEmojiStatus = .inputEmojiStatusCollectible(flags: flags, collectibleId: starGift.id, until: expirationDate)
|
||||
apiEmojiStatus = .inputEmojiStatusCollectible(.init(flags: flags, collectibleId: starGift.id, until: expirationDate))
|
||||
emojiStatus = PeerEmojiStatus(content: .starGift(id: starGift.id, fileId: file.fileId.id, title: starGift.title, slug: starGift.slug, patternFileId: patternFile.fileId.id, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor), expirationDate: expirationDate)
|
||||
} else {
|
||||
apiEmojiStatus = .emojiStatusEmpty
|
||||
@@ -143,7 +143,7 @@ public extension TelegramEngine {
|
||||
if let _ = expirationDate {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return Api.EmojiStatus.emojiStatus(flags: flags, documentId: file.fileId.id, until: expirationDate)
|
||||
return Api.EmojiStatus.emojiStatus(.init(flags: flags, documentId: file.fileId.id, until: expirationDate))
|
||||
}) ?? Api.EmojiStatus.emojiStatusEmpty))
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
return .single(.boolFalse)
|
||||
|
||||
@@ -22,10 +22,12 @@ public struct TermsOfServiceUpdate: Equatable {
|
||||
extension TermsOfServiceUpdate {
|
||||
init?(apiTermsOfService: Api.help.TermsOfService) {
|
||||
switch apiTermsOfService {
|
||||
case let .termsOfService(_, id, text, entities, minAgeConfirm):
|
||||
case let .termsOfService(termsOfServiceData):
|
||||
let (_, id, text, entities, minAgeConfirm) = (termsOfServiceData.flags, termsOfServiceData.id, termsOfServiceData.text, termsOfServiceData.entities, termsOfServiceData.minAgeConfirm)
|
||||
let idData: String
|
||||
switch id {
|
||||
case let .dataJSON(data):
|
||||
case let .dataJSON(dataJSONData):
|
||||
let data = dataJSONData.data
|
||||
idData = data
|
||||
}
|
||||
self.init(id: idData, text: text, entities: messageTextEntitiesFromApiEntities(entities), ageConfirmation: minAgeConfirm)
|
||||
@@ -34,7 +36,7 @@ extension TermsOfServiceUpdate {
|
||||
}
|
||||
|
||||
func _internal_acceptTermsOfService(account: Account, id: String) -> Signal<Void, NoError> {
|
||||
return account.network.request(Api.functions.help.acceptTermsOfService(id: .dataJSON(data: id)))
|
||||
return account.network.request(Api.functions.help.acceptTermsOfService(id: .dataJSON(.init(data: id))))
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
return .complete()
|
||||
}
|
||||
@@ -50,7 +52,8 @@ func managedTermsOfServiceUpdates(postbox: Postbox, network: Network, stateManag
|
||||
|> mapToSignal { [weak stateManager] result -> Signal<Void, NoError> in
|
||||
var updated: TermsOfServiceUpdate?
|
||||
switch result {
|
||||
case let .termsOfServiceUpdate(_, termsOfService):
|
||||
case let .termsOfServiceUpdate(termsOfServiceUpdateData):
|
||||
let (_, termsOfService) = (termsOfServiceUpdateData.expires, termsOfServiceUpdateData.termsOfService)
|
||||
updated = TermsOfServiceUpdate(apiTermsOfService: termsOfService)
|
||||
case .termsOfServiceUpdateEmpty:
|
||||
break
|
||||
|
||||
+3
-3
@@ -87,9 +87,9 @@ func _internal_updateNameColorAndEmoji(account: Account, nameColor: UpdateNameCo
|
||||
if let _ = backgroundEmojiId {
|
||||
flags |= (1 << 1)
|
||||
}
|
||||
inputRepliesColor = .peerColor(flags: flags, color: color.rawValue, backgroundEmojiId: backgroundEmojiId)
|
||||
inputRepliesColor = .peerColor(.init(flags: flags, color: color.rawValue, backgroundEmojiId: backgroundEmojiId))
|
||||
case let .collectible(collectibleColor):
|
||||
inputRepliesColor = .inputPeerColorCollectible(collectibleId: collectibleColor.collectibleId)
|
||||
inputRepliesColor = .inputPeerColorCollectible(.init(collectibleId: collectibleColor.collectibleId))
|
||||
}
|
||||
|
||||
var flagsProfile: Int32 = 0
|
||||
@@ -102,7 +102,7 @@ func _internal_updateNameColorAndEmoji(account: Account, nameColor: UpdateNameCo
|
||||
|
||||
return combineLatest(
|
||||
account.network.request(Api.functions.account.updateColor(flags: (1 << 2), color: inputRepliesColor)),
|
||||
account.network.request(Api.functions.account.updateColor(flags: (1 << 1) | (1 << 2), color: .peerColor(flags: flagsProfile, color: profileColor?.rawValue ?? 0, backgroundEmojiId: profileBackgroundEmojiId)))
|
||||
account.network.request(Api.functions.account.updateColor(flags: (1 << 1) | (1 << 2), color: .peerColor(.init(flags: flagsProfile, color: profileColor?.rawValue ?? 0, backgroundEmojiId: profileBackgroundEmojiId))))
|
||||
)
|
||||
|> mapError { _ -> UpdateNameColorAndEmojiError in
|
||||
return .generic
|
||||
|
||||
@@ -35,7 +35,8 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager<TelegramAc
|
||||
}
|
||||
|> mapToSignal { result -> Signal<Api.auth.LoginToken?, ExportAuthTransferTokenError> in
|
||||
switch result {
|
||||
case let .password(_, _, _, _, hint, _, _, _, _, _, _):
|
||||
case let .password(passwordData):
|
||||
let hint = passwordData.hint
|
||||
return account.postbox.transaction { transaction -> Api.auth.LoginToken? in
|
||||
transaction.setState(UnauthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, contents: .passwordEntry(hint: hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts)))
|
||||
return nil
|
||||
@@ -52,9 +53,11 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager<TelegramAc
|
||||
return .single(.passwordRequested(account))
|
||||
}
|
||||
switch result {
|
||||
case let .loginToken(expires, token):
|
||||
case let .loginToken(loginTokenData):
|
||||
let (expires, token) = (loginTokenData.expires, loginTokenData.token)
|
||||
return .single(.displayToken(AuthTransferExportedToken(value: token.makeData(), validUntil: expires)))
|
||||
case let .loginTokenMigrateTo(dcId, token):
|
||||
case let .loginTokenMigrateTo(loginTokenMigrateToData):
|
||||
let (dcId, token) = (loginTokenMigrateToData.dcId, loginTokenMigrateToData.token)
|
||||
let updatedAccount = account.changedMasterDatacenterId(accountManager: accountManager, masterDatacenterId: dcId)
|
||||
return updatedAccount
|
||||
|> castError(ExportAuthTransferTokenError.self)
|
||||
@@ -73,7 +76,8 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager<TelegramAc
|
||||
}
|
||||
|> mapToSignal { result -> Signal<Api.auth.LoginToken?, ExportAuthTransferTokenError> in
|
||||
switch result {
|
||||
case let .password(_, _, _, _, hint, _, _, _, _, _, _):
|
||||
case let .password(passwordData):
|
||||
let hint = passwordData.hint
|
||||
return updatedAccount.postbox.transaction { transaction -> Api.auth.LoginToken? in
|
||||
transaction.setState(UnauthorizedAccountState(isTestingEnvironment: updatedAccount.testingEnvironment, masterDatacenterId: updatedAccount.masterDatacenterId, contents: .passwordEntry(hint: hint ?? "", number: nil, code: nil, suggestReset: false, syncContacts: syncContacts)))
|
||||
return nil
|
||||
@@ -90,15 +94,17 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager<TelegramAc
|
||||
return .single(.passwordRequested(updatedAccount))
|
||||
}
|
||||
switch result {
|
||||
case let .loginTokenSuccess(authorization):
|
||||
case let .loginTokenSuccess(loginTokenSuccessData):
|
||||
let authorization = loginTokenSuccessData.authorization
|
||||
switch authorization {
|
||||
case let .authorization(_, _, _, futureAuthToken, user):
|
||||
case let .authorization(authorizationData):
|
||||
let (futureAuthToken, apiUser) = (authorizationData.futureAuthToken, authorizationData.user)
|
||||
if let futureAuthToken = futureAuthToken {
|
||||
storeFutureLoginToken(accountManager: accountManager, token: futureAuthToken.makeData())
|
||||
}
|
||||
|
||||
|
||||
return updatedAccount.postbox.transaction { transaction -> Signal<ExportAuthTransferTokenResult, ExportAuthTransferTokenError> in
|
||||
let user = TelegramUser(user: user)
|
||||
let user = TelegramUser(user: apiUser)
|
||||
let state = AuthorizedAccountState(isTestingEnvironment: updatedAccount.testingEnvironment, masterDatacenterId: updatedAccount.masterDatacenterId, peerId: user.id, state: nil, invalidatedChannels: [])
|
||||
initializedAppSettingsAfterLogin(transaction: transaction, appVersion: updatedAccount.networkArguments.appVersion, syncContacts: syncContacts)
|
||||
transaction.setState(state)
|
||||
@@ -118,15 +124,17 @@ func _internal_exportAuthTransferToken(accountManager: AccountManager<TelegramAc
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .loginTokenSuccess(authorization):
|
||||
case let .loginTokenSuccess(loginTokenSuccessData):
|
||||
let authorization = loginTokenSuccessData.authorization
|
||||
switch authorization {
|
||||
case let .authorization(_, _, _, futureAuthToken, user):
|
||||
case let .authorization(authorizationData):
|
||||
let (futureAuthToken, apiUser) = (authorizationData.futureAuthToken, authorizationData.user)
|
||||
if let futureAuthToken = futureAuthToken {
|
||||
storeFutureLoginToken(accountManager: accountManager, token: futureAuthToken.makeData())
|
||||
}
|
||||
|
||||
|
||||
return account.postbox.transaction { transaction -> Signal<ExportAuthTransferTokenResult, ExportAuthTransferTokenError> in
|
||||
let user = TelegramUser(user: user)
|
||||
let user = TelegramUser(user: apiUser)
|
||||
let state = AuthorizedAccountState(isTestingEnvironment: account.testingEnvironment, masterDatacenterId: account.masterDatacenterId, peerId: user.id, state: nil, invalidatedChannels: [])
|
||||
initializedAppSettingsAfterLogin(transaction: transaction, appVersion: account.networkArguments.appVersion, syncContacts: syncContacts)
|
||||
transaction.setState(state)
|
||||
|
||||
@@ -18,7 +18,7 @@ public enum RequestCancelAccountResetDataError {
|
||||
}
|
||||
|
||||
func _internal_requestCancelAccountResetData(network: Network, hash: String) -> Signal<CancelAccountResetData, RequestCancelAccountResetDataError> {
|
||||
return network.request(Api.functions.account.sendConfirmPhoneCode(hash: hash, settings: .codeSettings(flags: 0, logoutTokens: nil, token: nil, appSandbox: nil)), automaticFloodWait: false)
|
||||
return network.request(Api.functions.account.sendConfirmPhoneCode(hash: hash, settings: .codeSettings(.init(flags: 0, logoutTokens: nil, token: nil, appSandbox: nil))), automaticFloodWait: false)
|
||||
|> mapError { error -> RequestCancelAccountResetDataError in
|
||||
if error.errorDescription.hasPrefix("FLOOD_WAIT") {
|
||||
return .limitExceeded
|
||||
@@ -28,7 +28,8 @@ func _internal_requestCancelAccountResetData(network: Network, hash: String) ->
|
||||
}
|
||||
|> mapToSignal { sentCode -> Signal<CancelAccountResetData, RequestCancelAccountResetDataError> in
|
||||
switch sentCode {
|
||||
case let .sentCode(_, type, phoneCodeHash, nextType, timeout):
|
||||
case let .sentCode(sentCodeData):
|
||||
let (type, phoneCodeHash, nextType, timeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout)
|
||||
var parsedNextType: AuthorizationCodeNextType?
|
||||
if let nextType = nextType {
|
||||
parsedNextType = AuthorizationCodeNextType(apiType: nextType)
|
||||
@@ -51,7 +52,8 @@ func _internal_requestNextCancelAccountResetOption(network: Network, phoneNumber
|
||||
}
|
||||
|> mapToSignal { sentCode -> Signal<CancelAccountResetData, RequestCancelAccountResetDataError> in
|
||||
switch sentCode {
|
||||
case let .sentCode(_, type, phoneCodeHash, nextType, timeout):
|
||||
case let .sentCode(sentCodeData):
|
||||
let (type, phoneCodeHash, nextType, timeout) = (sentCodeData.type, sentCodeData.phoneCodeHash, sentCodeData.nextType, sentCodeData.timeout)
|
||||
var parsedNextType: AuthorizationCodeNextType?
|
||||
if let nextType = nextType {
|
||||
parsedNextType = AuthorizationCodeNextType(apiType: nextType)
|
||||
|
||||
@@ -116,7 +116,7 @@ public extension TelegramEngine {
|
||||
guard let kdfResult = passwordKDF(encryptionProvider: network.encryptionProvider, password: password, derivation: currentPasswordDerivation, srpSessionData: srpSessionData) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
return .single(.inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
return .single(.inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))))
|
||||
} else {
|
||||
return .single(nil)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ func _internal_twoStepVerificationConfiguration(account: Account) -> Signal<TwoS
|
||||
|> retryRequest
|
||||
|> map { result -> TwoStepVerificationConfiguration in
|
||||
switch result {
|
||||
case let .password(flags, currentAlgo, _, _, hint, emailUnconfirmedPattern, _, _, _, pendingResetDate, _):
|
||||
case let .password(passwordData):
|
||||
let (flags, currentAlgo, hint, emailUnconfirmedPattern, pendingResetDate) = (passwordData.flags, passwordData.currentAlgo, passwordData.hint, passwordData.emailUnconfirmedPattern, passwordData.pendingResetDate)
|
||||
if currentAlgo != nil {
|
||||
return .set(hint: hint ?? "", hasRecoveryEmail: (flags & (1 << 0)) != 0, pendingEmail: emailUnconfirmedPattern.flatMap({ TwoStepVerificationPendingEmail(pattern: $0, codeLength: nil) }), hasSecureValues: (flags & (1 << 1)) != 0, pendingResetTimestamp: pendingResetDate)
|
||||
} else {
|
||||
@@ -56,7 +57,7 @@ func _internal_requestTwoStepVerifiationSettings(network: Network, password: Str
|
||||
return .fail(.generic)
|
||||
}
|
||||
|
||||
return network.request(Api.functions.account.getPasswordSettings(password: .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))), automaticFloodWait: false)
|
||||
return network.request(Api.functions.account.getPasswordSettings(password: .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))), automaticFloodWait: false)
|
||||
|> mapError { error -> AuthorizationPasswordVerificationError in
|
||||
if error.errorDescription.hasPrefix("FLOOD_WAIT") {
|
||||
return .limitExceeded
|
||||
@@ -68,11 +69,13 @@ func _internal_requestTwoStepVerifiationSettings(network: Network, password: Str
|
||||
}
|
||||
|> mapToSignal { result -> Signal<TwoStepVerificationSettings, AuthorizationPasswordVerificationError> in
|
||||
switch result {
|
||||
case let .passwordSettings(_, email, secureSettings):
|
||||
case let .passwordSettings(passwordSettingsData):
|
||||
let (email, secureSettings) = (passwordSettingsData.email, passwordSettingsData.secureSettings)
|
||||
var parsedSecureSecret: TwoStepVerificationSecureSecret?
|
||||
if let secureSettings = secureSettings {
|
||||
switch secureSettings {
|
||||
case let .secureSecretSettings(secureAlgo, secureSecret, secureSecretId):
|
||||
case let .secureSecretSettings(secureSecretSettingsData):
|
||||
let (secureAlgo, secureSecret, secureSecretId) = (secureSecretSettingsData.secureAlgo, secureSecretSettingsData.secureSecret, secureSecretSettingsData.secureSecretId)
|
||||
if secureSecret.size != 32 {
|
||||
return .fail(.generic)
|
||||
}
|
||||
@@ -141,7 +144,7 @@ func _internal_updateTwoStepVerificationPassword(network: Network, currentPasswo
|
||||
let checkPassword: Api.InputCheckPasswordSRP
|
||||
if let currentPasswordDerivation = authData.currentPasswordDerivation, let srpSessionData = authData.srpSessionData {
|
||||
if let kdfResult = passwordKDF(encryptionProvider: network.encryptionProvider, password: currentPassword ?? "", derivation: currentPasswordDerivation, srpSessionData: srpSessionData) {
|
||||
checkPassword = .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))
|
||||
checkPassword = .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
} else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
@@ -156,7 +159,7 @@ func _internal_updateTwoStepVerificationPassword(network: Network, currentPasswo
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: .passwordInputSettings(flags: flags, newAlgo: .passwordKdfAlgoUnknown, newPasswordHash: Buffer(data: Data()), hint: "", email: "", newSecureSettings: nil)), automaticFloodWait: true)
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: .passwordInputSettings(.init(flags: flags, newAlgo: .passwordKdfAlgoUnknown, newPasswordHash: Buffer(data: Data()), hint: "", email: "", newSecureSettings: nil))), automaticFloodWait: true)
|
||||
|> mapError { _ -> UpdateTwoStepVerificationPasswordError in
|
||||
return .generic
|
||||
}
|
||||
@@ -189,10 +192,10 @@ func _internal_updateTwoStepVerificationPassword(network: Network, currentPasswo
|
||||
var updatedSecureSettings: Api.SecureSecretSettings?
|
||||
if let updatedSecureSecret = updatedSecureSecret {
|
||||
flags |= 1 << 2
|
||||
updatedSecureSettings = .secureSecretSettings(secureAlgo: updatedSecureSecret.derivation.apiAlgo, secureSecret: Buffer(data: updatedSecureSecret.data), secureSecretId: updatedSecureSecret.id)
|
||||
updatedSecureSettings = .secureSecretSettings(.init(secureAlgo: updatedSecureSecret.derivation.apiAlgo, secureSecret: Buffer(data: updatedSecureSecret.data), secureSecretId: updatedSecureSecret.id))
|
||||
}
|
||||
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: Api.account.PasswordInputSettings.passwordInputSettings(flags: flags, newAlgo: updatedPasswordDerivation.apiAlgo, newPasswordHash: Buffer(data: updatedPasswordHash), hint: hint, email: email, newSecureSettings: updatedSecureSettings)), automaticFloodWait: false)
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: Api.account.PasswordInputSettings.passwordInputSettings(.init(flags: flags, newAlgo: updatedPasswordDerivation.apiAlgo, newPasswordHash: Buffer(data: updatedPasswordHash), hint: hint, email: email, newSecureSettings: updatedSecureSettings))), automaticFloodWait: false)
|
||||
|> map { _ -> UpdateTwoStepVerificationPasswordResult in
|
||||
return .password(password: password, pendingEmail: nil)
|
||||
}
|
||||
@@ -245,14 +248,14 @@ func updateTwoStepVerificationSecureSecret(network: Network, password: String, s
|
||||
return .fail(.generic)
|
||||
}
|
||||
|
||||
let checkPassword: Api.InputCheckPasswordSRP = .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))
|
||||
let checkPassword: Api.InputCheckPasswordSRP = .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
|
||||
guard let (encryptedSecret, secretDerivation, secretId) = encryptedSecureSecret(secretData: secret, password: password, inputDerivation: authData.nextSecurePasswordDerivation) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
|
||||
let flags: Int32 = (1 << 2)
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: .passwordInputSettings(flags: flags, newAlgo: nil, newPasswordHash: nil, hint: "", email: "", newSecureSettings: .secureSecretSettings(secureAlgo: secretDerivation.apiAlgo, secureSecret: Buffer(data: encryptedSecret), secureSecretId: secretId))), automaticFloodWait: true)
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: .passwordInputSettings(.init(flags: flags, newAlgo: nil, newPasswordHash: nil, hint: "", email: "", newSecureSettings: .secureSecretSettings(.init(secureAlgo: secretDerivation.apiAlgo, secureSecret: Buffer(data: encryptedSecret), secureSecretId: secretId))))), automaticFloodWait: true)
|
||||
|> mapError { _ -> UpdateTwoStepVerificationSecureSecretError in
|
||||
return .generic
|
||||
}
|
||||
@@ -273,13 +276,13 @@ func _internal_updateTwoStepVerificationEmail(network: Network, currentPassword:
|
||||
guard let kdfResult = passwordKDF(encryptionProvider: network.encryptionProvider, password: currentPassword, derivation: currentPasswordDerivation, srpSessionData: srpSessionData) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
checkPassword = .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))
|
||||
checkPassword = .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
} else {
|
||||
checkPassword = .inputCheckPasswordEmpty
|
||||
}
|
||||
|
||||
let flags: Int32 = 1 << 1
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: Api.account.PasswordInputSettings.passwordInputSettings(flags: flags, newAlgo: nil, newPasswordHash: nil, hint: nil, email: updatedEmail, newSecureSettings: nil)), automaticFloodWait: false)
|
||||
return network.request(Api.functions.account.updatePasswordSettings(password: checkPassword, newSettings: Api.account.PasswordInputSettings.passwordInputSettings(.init(flags: flags, newAlgo: nil, newPasswordHash: nil, hint: nil, email: updatedEmail, newSecureSettings: nil))), automaticFloodWait: false)
|
||||
|> map { _ -> UpdateTwoStepVerificationPasswordResult in
|
||||
return .password(password: currentPassword, pendingEmail: nil)
|
||||
}
|
||||
@@ -327,7 +330,8 @@ func _internal_requestTwoStepVerificationPasswordRecoveryCode(network: Network)
|
||||
}
|
||||
|> map { result -> String in
|
||||
switch result {
|
||||
case let .passwordRecovery(emailPattern):
|
||||
case let .passwordRecovery(passwordRecoveryData):
|
||||
let (emailPattern) = (passwordRecoveryData.emailPattern)
|
||||
return emailPattern
|
||||
}
|
||||
}
|
||||
@@ -370,12 +374,13 @@ func _internal_requestTemporaryTwoStepPasswordToken(account: Account, password:
|
||||
return .fail(MTRpcError(errorCode: 400, errorDescription: "KDF_ERROR"))
|
||||
}
|
||||
|
||||
let checkPassword: Api.InputCheckPasswordSRP = .inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))
|
||||
let checkPassword: Api.InputCheckPasswordSRP = .inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
|
||||
return account.network.request(Api.functions.account.getTmpPassword(password: checkPassword, period: period), automaticFloodWait: false)
|
||||
|> map { result -> TemporaryTwoStepPasswordToken in
|
||||
switch result {
|
||||
case let .tmpPassword(tmpPassword, validUntil):
|
||||
case let .tmpPassword(tmpPasswordData):
|
||||
let (tmpPassword, validUntil) = (tmpPasswordData.tmpPassword, tmpPasswordData.validUntil)
|
||||
return TemporaryTwoStepPasswordToken(token: tmpPassword.makeData(), validUntilDate: validUntil, requiresBiometrics: requiresBiometrics)
|
||||
}
|
||||
}
|
||||
@@ -407,11 +412,13 @@ func _internal_requestTwoStepPasswordReset(network: Network) -> Signal<RequestTw
|
||||
return network.request(Api.functions.account.resetPassword(), automaticFloodWait: false)
|
||||
|> map { result -> RequestTwoStepPasswordResetResult in
|
||||
switch result {
|
||||
case let .resetPasswordFailedWait(retryDate):
|
||||
case let .resetPasswordFailedWait(resetPasswordFailedWaitData):
|
||||
let retryDate = resetPasswordFailedWaitData.retryDate
|
||||
return .error(reason: .limitExceeded(retryAtTimestamp: retryDate))
|
||||
case .resetPasswordOk:
|
||||
return .done
|
||||
case let .resetPasswordRequestedWait(untilDate):
|
||||
case let .resetPasswordRequestedWait(resetPasswordRequestedWaitData):
|
||||
let untilDate = resetPasswordRequestedWaitData.untilDate
|
||||
return .waitingForReset(resetAtTimestamp: untilDate)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,8 @@ public struct GroupCallSummary: Equatable {
|
||||
extension GroupCallInfo {
|
||||
init?(_ call: Api.GroupCall) {
|
||||
switch call {
|
||||
case let .groupCall(flags, id, accessHash, participantsCount, title, streamDcId, recordStartDate, scheduleDate, _, unmutedVideoLimit, _, _, sendPaidMessagesStars, defaultSendAs):
|
||||
case let .groupCall(groupCallData):
|
||||
let (flags, id, accessHash, participantsCount, title, streamDcId, recordStartDate, scheduleDate, _, unmutedVideoLimit, _, _, sendPaidMessagesStars, defaultSendAs) = (groupCallData.flags, groupCallData.id, groupCallData.accessHash, groupCallData.participantsCount, groupCallData.title, groupCallData.streamDcId, groupCallData.recordStartDate, groupCallData.scheduleDate, groupCallData.unmutedVideoCount, groupCallData.unmutedVideoLimit, groupCallData.version, groupCallData.inviteLink, groupCallData.sendPaidMessagesStars, groupCallData.defaultSendAs)
|
||||
self.init(
|
||||
id: id,
|
||||
accessHash: accessHash,
|
||||
@@ -185,11 +186,11 @@ extension InternalGroupCallReference {
|
||||
var apiInputGroupCall: Api.InputGroupCall {
|
||||
switch self {
|
||||
case let .id(id, accessHash):
|
||||
return .inputGroupCall(id: id, accessHash: accessHash)
|
||||
return .inputGroupCall(.init(id: id, accessHash: accessHash))
|
||||
case let .link(slug):
|
||||
return .inputGroupCallSlug(slug: slug)
|
||||
return .inputGroupCallSlug(.init(slug: slug))
|
||||
case let .message(id):
|
||||
return .inputGroupCallInviteMessage(msgId: id.id)
|
||||
return .inputGroupCallInviteMessage(.init(msgId: id.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,9 +200,9 @@ func _internal_getCurrentGroupCall(account: Account, reference: InternalGroupCal
|
||||
let inputCall: Api.InputGroupCall
|
||||
switch reference {
|
||||
case let .id(id, accessHash):
|
||||
inputCall = .inputGroupCall(id: id, accessHash: accessHash)
|
||||
inputCall = .inputGroupCall(.init(id: id, accessHash: accessHash))
|
||||
case let .link(slug):
|
||||
inputCall = .inputGroupCallSlug(slug: slug)
|
||||
inputCall = .inputGroupCallSlug(.init(slug: slug))
|
||||
case let .message(id):
|
||||
if id.peerId.namespace != Namespaces.Peer.CloudUser {
|
||||
return .fail(.generic)
|
||||
@@ -209,7 +210,7 @@ func _internal_getCurrentGroupCall(account: Account, reference: InternalGroupCal
|
||||
if id.namespace != Namespaces.Message.Cloud {
|
||||
return .fail(.generic)
|
||||
}
|
||||
inputCall = .inputGroupCallInviteMessage(msgId: id.id)
|
||||
inputCall = .inputGroupCallInviteMessage(.init(msgId: id.id))
|
||||
}
|
||||
return account.network.request(Api.functions.phone.getGroupCall(call: inputCall, limit: 4))
|
||||
|> mapError { _ -> GetCurrentGroupCallError in
|
||||
@@ -217,7 +218,8 @@ func _internal_getCurrentGroupCall(account: Account, reference: InternalGroupCal
|
||||
}
|
||||
|> mapToSignal { result -> Signal<GroupCallSummary?, GetCurrentGroupCallError> in
|
||||
switch result {
|
||||
case let .groupCall(call, participants, _, chats, users):
|
||||
case let .groupCall(groupCallData):
|
||||
let (call, participants, chats, users) = (groupCallData.call, groupCallData.participants, groupCallData.chats, groupCallData.users)
|
||||
return account.postbox.transaction { transaction -> GroupCallSummary? in
|
||||
guard let info = GroupCallInfo(call) else {
|
||||
return nil
|
||||
@@ -255,9 +257,9 @@ func _internal_getCurrentGroupCallInfo(account: Account, reference: InternalGrou
|
||||
let inputCall: Api.InputGroupCall
|
||||
switch reference {
|
||||
case let .id(id, accessHash):
|
||||
inputCall = .inputGroupCall(id: id, accessHash: accessHash)
|
||||
inputCall = .inputGroupCall(.init(id: id, accessHash: accessHash))
|
||||
case let .link(slug):
|
||||
inputCall = .inputGroupCallSlug(slug: slug)
|
||||
inputCall = .inputGroupCallSlug(.init(slug: slug))
|
||||
case let .message(id):
|
||||
if id.peerId.namespace != Namespaces.Peer.CloudUser {
|
||||
return .single(nil)
|
||||
@@ -265,7 +267,7 @@ func _internal_getCurrentGroupCallInfo(account: Account, reference: InternalGrou
|
||||
if id.namespace != Namespaces.Message.Cloud {
|
||||
return .single(nil)
|
||||
}
|
||||
inputCall = .inputGroupCallInviteMessage(msgId: id.id)
|
||||
inputCall = .inputGroupCallInviteMessage(.init(msgId: id.id))
|
||||
}
|
||||
return account.network.request(Api.functions.phone.getGroupCall(call: inputCall, limit: 4))
|
||||
|> map(Optional.init)
|
||||
@@ -277,9 +279,11 @@ func _internal_getCurrentGroupCallInfo(account: Account, reference: InternalGrou
|
||||
return .single(nil)
|
||||
}
|
||||
switch result {
|
||||
case let .groupCall(call, participants, _, chats, users):
|
||||
case let .groupCall(groupCallData):
|
||||
let (call, participants, chats, users) = (groupCallData.call, groupCallData.participants, groupCallData.chats, groupCallData.users)
|
||||
return account.postbox.transaction { transaction -> (participants: [PeerId], duration: Int32?)? in
|
||||
if case let .groupCallDiscarded(_, _, duration) = call {
|
||||
if case let .groupCallDiscarded(groupCallDiscardedData) = call {
|
||||
let (_, _, duration) = (groupCallDiscardedData.id, groupCallDiscardedData.accessHash, groupCallDiscardedData.duration)
|
||||
return ([], duration)
|
||||
}
|
||||
|
||||
@@ -336,7 +340,8 @@ func _internal_createGroupCall(account: Account, peerId: PeerId, title: String?,
|
||||
var parsedCall: GroupCallInfo?
|
||||
loop: for update in result.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCall(_, _, call):
|
||||
case let .updateGroupCall(updateGroupCallData):
|
||||
let call = updateGroupCallData.call
|
||||
parsedCall = GroupCallInfo(call)
|
||||
break loop
|
||||
default:
|
||||
@@ -373,7 +378,7 @@ public enum StartScheduledGroupCallError {
|
||||
}
|
||||
|
||||
func _internal_startScheduledGroupCall(account: Account, peerId: PeerId, callId: Int64, accessHash: Int64) -> Signal<GroupCallInfo, StartScheduledGroupCallError> {
|
||||
return account.network.request(Api.functions.phone.startScheduledGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash)))
|
||||
return account.network.request(Api.functions.phone.startScheduledGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash))))
|
||||
|> mapError { error -> StartScheduledGroupCallError in
|
||||
return .generic
|
||||
}
|
||||
@@ -381,7 +386,8 @@ func _internal_startScheduledGroupCall(account: Account, peerId: PeerId, callId:
|
||||
var parsedCall: GroupCallInfo?
|
||||
loop: for update in result.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCall(_, _, call):
|
||||
case let .updateGroupCall(updateGroupCallData):
|
||||
let call = updateGroupCallData.call
|
||||
parsedCall = GroupCallInfo(call)
|
||||
break loop
|
||||
default:
|
||||
@@ -438,7 +444,8 @@ func _internal_toggleScheduledGroupCallSubscription(account: Account, peerId: Pe
|
||||
var parsedCall: GroupCallInfo?
|
||||
loop: for update in result.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCall(_, _, call):
|
||||
case let .updateGroupCall(updateGroupCallData):
|
||||
let call = updateGroupCallData.call
|
||||
parsedCall = GroupCallInfo(call)
|
||||
break loop
|
||||
default:
|
||||
@@ -552,7 +559,8 @@ func _internal_getGroupCallParticipants(account: Account, reference: InternalGro
|
||||
|
||||
if let result {
|
||||
switch result {
|
||||
case let .groupParticipants(count, participants, nextOffset, chats, users, apiVersion):
|
||||
case let .groupParticipants(groupParticipantsData):
|
||||
let (count, participants, nextOffset, chats, users, apiVersion) = (groupParticipantsData.count, groupParticipantsData.participants, groupParticipantsData.nextOffset, groupParticipantsData.chats, groupParticipantsData.users, groupParticipantsData.version)
|
||||
totalCount = Int(count)
|
||||
version = apiVersion
|
||||
|
||||
@@ -692,7 +700,7 @@ func _internal_joinGroupCall(account: Account, peerId: PeerId?, joinAs: PeerId?,
|
||||
flags |= (1 << 3)
|
||||
}
|
||||
|
||||
let joinRequest = account.network.request(Api.functions.phone.joinGroupCall(flags: flags, call: reference.apiInputGroupCall, joinAs: inputJoinAs, inviteHash: inviteHash, publicKey: e2eData?.publicKey.value, block: (e2eData?.block).flatMap({ Buffer.init(data: $0) }), params: .dataJSON(data: joinPayload)))
|
||||
let joinRequest = account.network.request(Api.functions.phone.joinGroupCall(flags: flags, call: reference.apiInputGroupCall, joinAs: inputJoinAs, inviteHash: inviteHash, publicKey: e2eData?.publicKey.value, block: (e2eData?.block).flatMap({ Buffer.init(data: $0) }), params: .dataJSON(.init(data: joinPayload))))
|
||||
|> `catch` { error -> Signal<Api.Updates, InternalJoinError> in
|
||||
if error.errorDescription == "GROUPCALL_ANONYMOUS_FORBIDDEN" {
|
||||
return .fail(.error(.anonymousNotAllowed))
|
||||
@@ -779,11 +787,13 @@ func _internal_joinGroupCall(account: Account, peerId: PeerId?, joinAs: PeerId?,
|
||||
var maybeParsedClientParams: String?
|
||||
loop: for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCall(_, _, call):
|
||||
case let .updateGroupCall(updateGroupCallData):
|
||||
let call = updateGroupCallData.call
|
||||
maybeParsedCall = GroupCallInfo(call)
|
||||
|
||||
|
||||
switch call {
|
||||
case let .groupCall(flags, _, _, _, title, _, recordStartDate, scheduleDate, _, unmutedVideoLimit, _, _, sendPaidMessagesStars, defaultSendAs):
|
||||
case let .groupCall(groupCallData):
|
||||
let (flags, _, _, _, title, _, recordStartDate, scheduleDate, _, unmutedVideoLimit, _, _, sendPaidMessagesStars, defaultSendAs) = (groupCallData.flags, groupCallData.id, groupCallData.accessHash, groupCallData.participantsCount, groupCallData.title, groupCallData.streamDcId, groupCallData.recordStartDate, groupCallData.scheduleDate, groupCallData.unmutedVideoCount, groupCallData.unmutedVideoLimit, groupCallData.version, groupCallData.inviteLink, groupCallData.sendPaidMessagesStars, groupCallData.defaultSendAs)
|
||||
let isMin = (flags & (1 << 19)) != 0
|
||||
let isMuted = (flags & (1 << 1)) != 0
|
||||
let canChange = (flags & (1 << 2)) != 0
|
||||
@@ -803,9 +813,11 @@ func _internal_joinGroupCall(account: Account, peerId: PeerId?, joinAs: PeerId?,
|
||||
default:
|
||||
break
|
||||
}
|
||||
case let .updateGroupCallConnection(_, params):
|
||||
case let .updateGroupCallConnection(updateGroupCallConnectionData):
|
||||
let params = updateGroupCallConnectionData.params
|
||||
switch params {
|
||||
case let .dataJSON(data):
|
||||
case let .dataJSON(dataJSONData):
|
||||
let data = dataJSONData.data
|
||||
maybeParsedClientParams = data
|
||||
}
|
||||
default:
|
||||
@@ -859,10 +871,12 @@ func _internal_joinGroupCall(account: Account, peerId: PeerId?, joinAs: PeerId?,
|
||||
|
||||
for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCallParticipants(_, participants, _):
|
||||
case let .updateGroupCallParticipants(updateGroupCallParticipantsData):
|
||||
let participants = updateGroupCallParticipantsData.participants
|
||||
loop: for participant in participants {
|
||||
switch participant {
|
||||
case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal):
|
||||
case let .groupCallParticipant(groupCallParticipantData):
|
||||
let (flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal) = (groupCallParticipantData.flags, groupCallParticipantData.peer, groupCallParticipantData.date, groupCallParticipantData.activeDate, groupCallParticipantData.source, groupCallParticipantData.volume, groupCallParticipantData.about, groupCallParticipantData.raiseHandRating, groupCallParticipantData.video, groupCallParticipantData.presentation, groupCallParticipantData.paidStarsTotal)
|
||||
let peerId: PeerId = apiPeerId.peerId
|
||||
let ssrc = UInt32(bitPattern: source)
|
||||
guard let peer = transaction.getPeer(peerId) else {
|
||||
@@ -905,7 +919,8 @@ func _internal_joinGroupCall(account: Account, peerId: PeerId?, joinAs: PeerId?,
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .updateGroupCallChainBlocks(_, subChainId, blocks, nextOffset):
|
||||
case let .updateGroupCallChainBlocks(updateGroupCallChainBlocksData):
|
||||
let (subChainId, blocks, nextOffset) = (updateGroupCallChainBlocksData.subChainId, updateGroupCallChainBlocksData.blocks, updateGroupCallChainBlocksData.nextOffset)
|
||||
if subChainId == 0 {
|
||||
e2eSubChain0State = (offset: Int(nextOffset), blocks: blocks.map { $0.makeData() })
|
||||
} else {
|
||||
@@ -1018,7 +1033,7 @@ func _internal_removeGroupCallBlockchainParticipants(account: Account, callId: I
|
||||
case .cleanup:
|
||||
flags |= 1 << 0
|
||||
}
|
||||
return account.network.request(Api.functions.phone.deleteConferenceCallParticipants(flags: flags, call: .inputGroupCall(id: callId, accessHash: accessHash), ids: participantIds, block: Buffer(data: block)))
|
||||
return account.network.request(Api.functions.phone.deleteConferenceCallParticipants(flags: flags, call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), ids: participantIds, block: Buffer(data: block)))
|
||||
|> map { updates -> RemoveGroupCallBlockchainParticipantsResult in
|
||||
account.stateManager.addUpdates(updates)
|
||||
return .success
|
||||
@@ -1034,7 +1049,7 @@ public struct JoinGroupCallAsScreencastResult {
|
||||
}
|
||||
|
||||
func _internal_joinGroupCallAsScreencast(account: Account, callId: Int64, accessHash: Int64, joinPayload: String) -> Signal<JoinGroupCallAsScreencastResult, JoinGroupCallError> {
|
||||
return account.network.request(Api.functions.phone.joinGroupCallPresentation(call: .inputGroupCall(id: callId, accessHash: accessHash), params: .dataJSON(data: joinPayload)))
|
||||
return account.network.request(Api.functions.phone.joinGroupCallPresentation(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), params: .dataJSON(.init(data: joinPayload))))
|
||||
|> mapError { _ -> JoinGroupCallError in
|
||||
return .generic
|
||||
}
|
||||
@@ -1044,9 +1059,11 @@ func _internal_joinGroupCallAsScreencast(account: Account, callId: Int64, access
|
||||
var maybeParsedClientParams: String?
|
||||
loop: for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCallConnection(_, params):
|
||||
case let .updateGroupCallConnection(updateGroupCallConnectionData):
|
||||
let params = updateGroupCallConnectionData.params
|
||||
switch params {
|
||||
case let .dataJSON(data):
|
||||
case let .dataJSON(dataJSONData):
|
||||
let data = dataJSONData.data
|
||||
maybeParsedClientParams = data
|
||||
}
|
||||
default:
|
||||
@@ -1082,7 +1099,7 @@ public enum LeaveGroupCallAsScreencastError {
|
||||
}
|
||||
|
||||
func _internal_leaveGroupCallAsScreencast(account: Account, callId: Int64, accessHash: Int64) -> Signal<Never, LeaveGroupCallAsScreencastError> {
|
||||
return account.network.request(Api.functions.phone.leaveGroupCallPresentation(call: .inputGroupCall(id: callId, accessHash: accessHash)))
|
||||
return account.network.request(Api.functions.phone.leaveGroupCallPresentation(call: .inputGroupCall(.init(id: callId, accessHash: accessHash))))
|
||||
|> mapError { _ -> LeaveGroupCallAsScreencastError in
|
||||
return .generic
|
||||
}
|
||||
@@ -1098,7 +1115,7 @@ public enum LeaveGroupCallError {
|
||||
}
|
||||
|
||||
func _internal_leaveGroupCall(account: Account, callId: Int64, accessHash: Int64, source: UInt32) -> Signal<Never, LeaveGroupCallError> {
|
||||
return account.network.request(Api.functions.phone.leaveGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash), source: Int32(bitPattern: source)))
|
||||
return account.network.request(Api.functions.phone.leaveGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), source: Int32(bitPattern: source)))
|
||||
|> mapError { _ -> LeaveGroupCallError in
|
||||
return .generic
|
||||
}
|
||||
@@ -1114,7 +1131,7 @@ public enum StopGroupCallError {
|
||||
}
|
||||
|
||||
func _internal_stopGroupCall(account: Account, peerId: PeerId?, callId: Int64, accessHash: Int64) -> Signal<Never, StopGroupCallError> {
|
||||
return account.network.request(Api.functions.phone.discardGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash)))
|
||||
return account.network.request(Api.functions.phone.discardGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash))))
|
||||
|> mapError { _ -> StopGroupCallError in
|
||||
return .generic
|
||||
}
|
||||
@@ -1158,7 +1175,7 @@ func _internal_stopGroupCall(account: Account, peerId: PeerId?, callId: Int64, a
|
||||
}
|
||||
|
||||
func _internal_checkGroupCall(account: Account, callId: Int64, accessHash: Int64, ssrcs: [UInt32]) -> Signal<[UInt32], NoError> {
|
||||
return account.network.request(Api.functions.phone.checkGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash), sources: ssrcs.map(Int32.init(bitPattern:))))
|
||||
return account.network.request(Api.functions.phone.checkGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), sources: ssrcs.map(Int32.init(bitPattern:))))
|
||||
|> `catch` { _ -> Signal<[Int32], NoError> in
|
||||
return .single([])
|
||||
}
|
||||
@@ -2481,15 +2498,17 @@ public final class GroupCallParticipantsContext {
|
||||
guard let strongSelf = self else {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if let updates = updates {
|
||||
var stateUpdates: [GroupCallParticipantsContext.Update] = []
|
||||
|
||||
|
||||
loop: for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCallParticipants(call, participants, version):
|
||||
case let .updateGroupCallParticipants(updateGroupCallParticipantsData):
|
||||
let (call, participants, version) = (updateGroupCallParticipantsData.call, updateGroupCallParticipantsData.participants, updateGroupCallParticipantsData.version)
|
||||
switch call {
|
||||
case let .inputGroupCall(updateCallId, _):
|
||||
case let .inputGroupCall(inputGroupCallData):
|
||||
let updateCallId = inputGroupCallData.id
|
||||
if updateCallId != id {
|
||||
continue loop
|
||||
}
|
||||
@@ -2501,9 +2520,9 @@ public final class GroupCallParticipantsContext {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
strongSelf.addUpdates(updates: stateUpdates)
|
||||
|
||||
|
||||
strongSelf.account.stateManager.addUpdates(updates)
|
||||
} else {
|
||||
strongSelf.stateValue.overlayState.pendingMuteStateChanges.removeValue(forKey: peerId)
|
||||
@@ -2575,9 +2594,11 @@ public final class GroupCallParticipantsContext {
|
||||
|
||||
loop: for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCallParticipants(call, participants, version):
|
||||
case let .updateGroupCallParticipants(updateGroupCallParticipantsData):
|
||||
let (call, participants, version) = (updateGroupCallParticipantsData.call, updateGroupCallParticipantsData.participants, updateGroupCallParticipantsData.version)
|
||||
switch call {
|
||||
case let .inputGroupCall(updateCallId, _):
|
||||
case let .inputGroupCall(inputGroupCallData):
|
||||
let updateCallId = inputGroupCallData.id
|
||||
if updateCallId != id {
|
||||
continue loop
|
||||
}
|
||||
@@ -2722,7 +2743,8 @@ public final class GroupCallParticipantsContext {
|
||||
extension GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate {
|
||||
init(_ apiParticipant: Api.GroupCallParticipant) {
|
||||
switch apiParticipant {
|
||||
case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal):
|
||||
case let .groupCallParticipant(groupCallParticipantData):
|
||||
let (flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal) = (groupCallParticipantData.flags, groupCallParticipantData.peer, groupCallParticipantData.date, groupCallParticipantData.activeDate, groupCallParticipantData.source, groupCallParticipantData.volume, groupCallParticipantData.about, groupCallParticipantData.raiseHandRating, groupCallParticipantData.video, groupCallParticipantData.presentation, groupCallParticipantData.paidStarsTotal)
|
||||
let peerId: PeerId = apiPeerId.peerId
|
||||
let ssrc = UInt32(bitPattern: source)
|
||||
let muted = (flags & (1 << 0)) != 0
|
||||
@@ -2801,7 +2823,7 @@ func _internal_inviteToGroupCall(account: Account, callId: Int64, accessHash: In
|
||||
return .fail(.generic)
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.phone.inviteToGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash), users: [apiUser]))
|
||||
return account.network.request(Api.functions.phone.inviteToGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), users: [apiUser]))
|
||||
|> mapError { _ -> InviteToGroupCallError in
|
||||
return .generic
|
||||
}
|
||||
@@ -2831,7 +2853,8 @@ func _internal_groupCallInviteLinks(account: Account, reference: InternalGroupCa
|
||||
return .single(nil)
|
||||
}
|
||||
|> mapToSignal { result -> Signal<String?, NoError> in
|
||||
if let result = result, case let .exportedGroupCallInvite(link) = result {
|
||||
if let result = result, case let .exportedGroupCallInvite(exportedGroupCallInviteData) = result {
|
||||
let link = exportedGroupCallInviteData.link
|
||||
return .single(link)
|
||||
}
|
||||
return .single(nil)
|
||||
@@ -2843,7 +2866,8 @@ func _internal_groupCallInviteLinks(account: Account, reference: InternalGroupCa
|
||||
return .single(nil)
|
||||
}
|
||||
|> mapToSignal { result -> Signal<String?, NoError> in
|
||||
if let result = result, case let .exportedGroupCallInvite(link) = result {
|
||||
if let result = result, case let .exportedGroupCallInvite(exportedGroupCallInviteData) = result {
|
||||
let link = exportedGroupCallInviteData.link
|
||||
return .single(link)
|
||||
}
|
||||
return .single(nil)
|
||||
@@ -2875,7 +2899,7 @@ public enum EditGroupCallTitleError {
|
||||
}
|
||||
|
||||
func _internal_editGroupCallTitle(account: Account, callId: Int64, accessHash: Int64, title: String) -> Signal<Never, EditGroupCallTitleError> {
|
||||
return account.network.request(Api.functions.phone.editGroupCallTitle(call: .inputGroupCall(id: callId, accessHash: accessHash), title: title)) |> mapError { _ -> EditGroupCallTitleError in
|
||||
return account.network.request(Api.functions.phone.editGroupCallTitle(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), title: title)) |> mapError { _ -> EditGroupCallTitleError in
|
||||
return .generic
|
||||
}
|
||||
|> mapToSignal { result -> Signal<Never, EditGroupCallTitleError> in
|
||||
@@ -2902,18 +2926,21 @@ func _internal_groupCallDisplayAsAvailablePeers(accountPeerId: PeerId, network:
|
||||
return .single([])
|
||||
}
|
||||
switch result {
|
||||
case let .joinAsPeers(_, chats, users):
|
||||
case let .joinAsPeers(joinAsPeersData):
|
||||
let (chats, users) = (joinAsPeersData.chats, joinAsPeersData.users)
|
||||
return postbox.transaction { transaction -> [FoundPeer] in
|
||||
var subscribers: [PeerId: Int32] = [:]
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
for chat in chats {
|
||||
if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
}
|
||||
case let .chat(_, _, _, _, participantsCount, _, _, _, _, _):
|
||||
case let .chat(chatData):
|
||||
let participantsCount = chatData.participantsCount
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
default:
|
||||
break
|
||||
@@ -3049,7 +3076,7 @@ public final class AudioBroadcastDataSource {
|
||||
}
|
||||
|
||||
func _internal_getAudioBroadcastDataSource(account: Account, callId: Int64, accessHash: Int64) -> Signal<AudioBroadcastDataSource?, NoError> {
|
||||
return account.network.request(Api.functions.phone.getGroupCall(call: .inputGroupCall(id: callId, accessHash: accessHash), limit: 4))
|
||||
return account.network.request(Api.functions.phone.getGroupCall(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), limit: 4))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.phone.GroupCall?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -3059,7 +3086,8 @@ func _internal_getAudioBroadcastDataSource(account: Account, callId: Int64, acce
|
||||
return .single(nil)
|
||||
}
|
||||
switch result {
|
||||
case let .groupCall(call, _, _, _, _):
|
||||
case let .groupCall(groupCallData):
|
||||
let call = groupCallData.call
|
||||
if let datacenterId = GroupCallInfo(call)?.streamDcId.flatMap(Int.init) {
|
||||
return account.network.download(datacenterId: datacenterId, isMedia: true, tag: nil)
|
||||
|> map { download -> AudioBroadcastDataSource? in
|
||||
@@ -3100,10 +3128,11 @@ func _internal_getAudioBroadcastPart(dataSource: AudioBroadcastDataSource, callI
|
||||
return .single(GetAudioBroadcastPartResult(status: .notReady, responseTimestamp: Double(timestampIdMilliseconds) / 1000.0))
|
||||
}
|
||||
|
||||
return dataSource.download.requestWithAdditionalData(Api.functions.upload.getFile(flags: 0, location: .inputGroupCallStream(flags: 0, call: .inputGroupCall(id: callId, accessHash: accessHash), timeMs: timestampIdMilliseconds, scale: scale, videoChannel: nil, videoQuality: nil), offset: 0, limit: 128 * 1024), automaticFloodWait: false, failOnServerErrors: true)
|
||||
return dataSource.download.requestWithAdditionalData(Api.functions.upload.getFile(flags: 0, location: .inputGroupCallStream(.init(flags: 0, call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), timeMs: timestampIdMilliseconds, scale: scale, videoChannel: nil, videoQuality: nil)), offset: 0, limit: 128 * 1024), automaticFloodWait: false, failOnServerErrors: true)
|
||||
|> map { result, responseTimestamp -> GetAudioBroadcastPartResult in
|
||||
switch result {
|
||||
case let .file(_, _, bytes):
|
||||
case let .file(fileData):
|
||||
let (bytes) = (fileData.bytes)
|
||||
return GetAudioBroadcastPartResult(
|
||||
status: .data(bytes.makeData()),
|
||||
responseTimestamp: responseTimestamp
|
||||
@@ -3153,10 +3182,11 @@ func _internal_getVideoBroadcastPart(dataSource: AudioBroadcastDataSource, callI
|
||||
return .single(GetAudioBroadcastPartResult(status: .notReady, responseTimestamp: Double(timestampIdMilliseconds) / 1000.0))
|
||||
}
|
||||
|
||||
return dataSource.download.requestWithAdditionalData(Api.functions.upload.getFile(flags: 0, location: .inputGroupCallStream(flags: 1 << 0, call: .inputGroupCall(id: callId, accessHash: accessHash), timeMs: timestampIdMilliseconds, scale: scale, videoChannel: channelId, videoQuality: quality), offset: 0, limit: 512 * 1024), automaticFloodWait: false, failOnServerErrors: true)
|
||||
return dataSource.download.requestWithAdditionalData(Api.functions.upload.getFile(flags: 0, location: .inputGroupCallStream(.init(flags: 1 << 0, call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), timeMs: timestampIdMilliseconds, scale: scale, videoChannel: channelId, videoQuality: quality)), offset: 0, limit: 512 * 1024), automaticFloodWait: false, failOnServerErrors: true)
|
||||
|> map { result, responseTimestamp -> GetAudioBroadcastPartResult in
|
||||
switch result {
|
||||
case let .file(_, _, bytes):
|
||||
case let .file(fileData):
|
||||
let (bytes) = (fileData.bytes)
|
||||
return GetAudioBroadcastPartResult(
|
||||
status: .data(bytes.makeData()),
|
||||
responseTimestamp: responseTimestamp
|
||||
@@ -3196,7 +3226,8 @@ func _internal_getVideoBroadcastPart(dataSource: AudioBroadcastDataSource, callI
|
||||
extension GroupCallParticipantsContext.Participant {
|
||||
init?(_ apiParticipant: Api.GroupCallParticipant, transaction: Transaction) {
|
||||
switch apiParticipant {
|
||||
case let .groupCallParticipant(flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal):
|
||||
case let .groupCallParticipant(groupCallParticipantData):
|
||||
let (flags, apiPeerId, date, activeDate, source, volume, about, raiseHandRating, video, presentation, paidStarsTotal) = (groupCallParticipantData.flags, groupCallParticipantData.peer, groupCallParticipantData.date, groupCallParticipantData.activeDate, groupCallParticipantData.source, groupCallParticipantData.volume, groupCallParticipantData.about, groupCallParticipantData.raiseHandRating, groupCallParticipantData.video, groupCallParticipantData.presentation, groupCallParticipantData.paidStarsTotal)
|
||||
let peerId: PeerId = apiPeerId.peerId
|
||||
let ssrc = UInt32(bitPattern: source)
|
||||
guard let peer = transaction.getPeer(peerId) else {
|
||||
@@ -3211,7 +3242,7 @@ extension GroupCallParticipantsContext.Participant {
|
||||
} else if mutedByYou {
|
||||
muteState = GroupCallParticipantsContext.Participant.MuteState(canUnmute: false, mutedByYou: mutedByYou)
|
||||
}
|
||||
|
||||
|
||||
var videoDescription = video.flatMap(GroupCallParticipantsContext.Participant.VideoDescription.init)
|
||||
var presentationDescription = presentation.flatMap(GroupCallParticipantsContext.Participant.VideoDescription.init)
|
||||
if muteState?.canUnmute == false {
|
||||
@@ -3244,11 +3275,13 @@ extension GroupCallParticipantsContext.Participant {
|
||||
private extension GroupCallParticipantsContext.Participant.VideoDescription {
|
||||
init(_ apiVideo: Api.GroupCallParticipantVideo) {
|
||||
switch apiVideo {
|
||||
case let .groupCallParticipantVideo(flags, endpoint, sourceGroups, audioSource):
|
||||
case let .groupCallParticipantVideo(groupCallParticipantVideoData):
|
||||
let (flags, endpoint, sourceGroups, audioSource) = (groupCallParticipantVideoData.flags, groupCallParticipantVideoData.endpoint, groupCallParticipantVideoData.sourceGroups, groupCallParticipantVideoData.audioSource)
|
||||
var parsedSsrcGroups: [SsrcGroup] = []
|
||||
for group in sourceGroups {
|
||||
switch group {
|
||||
case let .groupCallParticipantVideoSourceGroup(semantics, sources):
|
||||
case let .groupCallParticipantVideoSourceGroup(groupCallParticipantVideoSourceGroupData):
|
||||
let (semantics, sources) = (groupCallParticipantVideoSourceGroupData.semantics, groupCallParticipantVideoSourceGroupData.sources)
|
||||
parsedSsrcGroups.append(SsrcGroup(semantics: semantics, ssrcs: sources.map(UInt32.init(bitPattern:))))
|
||||
}
|
||||
}
|
||||
@@ -3287,7 +3320,8 @@ func _internal_getGroupCallStreamCredentials(account: Account, peerId: PeerId, i
|
||||
}
|
||||
|> map { result -> GroupCallStreamCredentials in
|
||||
switch result {
|
||||
case let .groupCallStreamRtmpUrl(url, key):
|
||||
case let .groupCallStreamRtmpUrl(groupCallStreamRtmpUrlData):
|
||||
let (url, key) = (groupCallStreamRtmpUrlData.url, groupCallStreamRtmpUrlData.key)
|
||||
return GroupCallStreamCredentials(url: url, streamKey: key)
|
||||
}
|
||||
}
|
||||
@@ -3317,7 +3351,8 @@ func _internal_createConferenceCall(postbox: Postbox, network: Network, accountP
|
||||
}
|
||||
|> mapToSignal { result in
|
||||
for update in result.allUpdates {
|
||||
if case let .updateGroupCall(_, _, call) = update {
|
||||
if case let .updateGroupCall(updateGroupCallData) = update {
|
||||
let call = updateGroupCallData.call
|
||||
return postbox.transaction { transaction -> Signal<EngineCreatedGroupCall, CreateConferenceCallError> in
|
||||
guard let info = GroupCallInfo(call) else {
|
||||
return .fail(.generic)
|
||||
@@ -3327,14 +3362,15 @@ func _internal_createConferenceCall(postbox: Postbox, network: Network, accountP
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
let speakerInvite: Signal<EngineCreatedGroupCall, CreateConferenceCallError> = network.request(Api.functions.phone.exportGroupCallInvite(flags: 1 << 0, call: .inputGroupCall(id: info.id, accessHash: info.accessHash)))
|
||||
let speakerInvite: Signal<EngineCreatedGroupCall, CreateConferenceCallError> = network.request(Api.functions.phone.exportGroupCallInvite(flags: 1 << 0, call: .inputGroupCall(.init(id: info.id, accessHash: info.accessHash))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.phone.ExportedGroupCallInvite?, NoError> in
|
||||
return .single(nil)
|
||||
}
|
||||
|> castError(CreateConferenceCallError.self)
|
||||
|> mapToSignal { result -> Signal<EngineCreatedGroupCall, CreateConferenceCallError> in
|
||||
if let result, case let .exportedGroupCallInvite(link) = result {
|
||||
if let result, case let .exportedGroupCallInvite(exportedGroupCallInviteData) = result {
|
||||
let link = exportedGroupCallInviteData.link
|
||||
let slug = link.components(separatedBy: "/").last ?? link
|
||||
return .single(EngineCreatedGroupCall(
|
||||
slug: slug,
|
||||
@@ -3397,7 +3433,8 @@ func _internal_pollConferenceCallBlockchain(network: Network, reference: Interna
|
||||
var nextOffset: Int?
|
||||
for update in result.allUpdates {
|
||||
switch update {
|
||||
case let .updateGroupCallChainBlocks(_, updateSubChainId, updateBlocks, updateNextOffset):
|
||||
case let .updateGroupCallChainBlocks(updateGroupCallChainBlocksData):
|
||||
let (updateSubChainId, updateBlocks, updateNextOffset) = (updateGroupCallChainBlocksData.subChainId, updateGroupCallChainBlocksData.blocks, updateGroupCallChainBlocksData.nextOffset)
|
||||
if updateSubChainId == Int32(subChainId) {
|
||||
blocks.append(contentsOf: updateBlocks.map { $0.makeData() })
|
||||
nextOffset = Int(updateNextOffset)
|
||||
@@ -3414,7 +3451,7 @@ func _internal_pollConferenceCallBlockchain(network: Network, reference: Interna
|
||||
}
|
||||
|
||||
func _internal_sendConferenceCallBroadcast(account: Account, callId: Int64, accessHash: Int64, block: Data) -> Signal<Never, NoError> {
|
||||
return account.network.request(Api.functions.phone.sendConferenceCallBroadcast(call: .inputGroupCall(id: callId, accessHash: accessHash), block: Buffer(data: block)))
|
||||
return account.network.request(Api.functions.phone.sendConferenceCallBroadcast(call: .inputGroupCall(.init(id: callId, accessHash: accessHash)), block: Buffer(data: block)))
|
||||
|> retry(retryOnError: { _ in
|
||||
return true
|
||||
}, delayIncrement: 0.1, maxDelay: 1.0, maxRetries: 5, onQueue: Queue.concurrentDefaultQueue())
|
||||
@@ -4098,11 +4135,13 @@ public final class GroupCallMessagesContext {
|
||||
return postbox.transaction { transaction -> (Api.phone.GroupCallStars, [PeerId: Peer])? in
|
||||
var peers: [PeerId: Peer] = [:]
|
||||
switch result {
|
||||
case let .groupCallStars(_, topDonors, chats, users):
|
||||
case let .groupCallStars(groupCallStarsData):
|
||||
let (topDonors, chats, users) = (groupCallStarsData.topDonors, groupCallStarsData.chats, groupCallStarsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(chats: chats, users: users))
|
||||
for topDonor in topDonors {
|
||||
switch topDonor {
|
||||
case let .groupCallDonor(_, peerId, _):
|
||||
case let .groupCallDonor(groupCallDonorData):
|
||||
let (_, peerId, _) = (groupCallDonorData.flags, groupCallDonorData.peerId, groupCallDonorData.stars)
|
||||
if let peerId {
|
||||
if peers[peerId.peerId] == nil, let peer = transaction.getPeer(peerId.peerId) {
|
||||
peers[peer.id] = peer
|
||||
@@ -4120,11 +4159,13 @@ public final class GroupCallMessagesContext {
|
||||
}
|
||||
if let (result, _) = result {
|
||||
switch result {
|
||||
case let .groupCallStars(totalStars, topDonors, _, _):
|
||||
case let .groupCallStars(groupCallStarsData):
|
||||
let (totalStars, topDonors) = (groupCallStarsData.totalStars, groupCallStarsData.topDonors)
|
||||
var state = self.state
|
||||
state.topStars = topDonors.map { topDonor in
|
||||
switch topDonor {
|
||||
case let .groupCallDonor(flags, peerId, stars):
|
||||
case let .groupCallDonor(groupCallDonorData):
|
||||
let (flags, peerId, stars) = (groupCallDonorData.flags, groupCallDonorData.peerId, groupCallDonorData.stars)
|
||||
return TopStarsItem(
|
||||
peerId: peerId?.peerId,
|
||||
amount: stars,
|
||||
@@ -4352,10 +4393,10 @@ public final class GroupCallMessagesContext {
|
||||
flags: flags,
|
||||
call: self.reference.apiInputGroupCall,
|
||||
randomId: randomId,
|
||||
message: .textWithEntities(
|
||||
message: .textWithEntities(.init(
|
||||
text: text,
|
||||
entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary())
|
||||
),
|
||||
)),
|
||||
allowPaidStars: paidStars,
|
||||
sendAs: sendAs
|
||||
)) |> deliverOn(self.queue)).startStrict(next: { [weak self] updates in
|
||||
@@ -4364,7 +4405,8 @@ public final class GroupCallMessagesContext {
|
||||
}
|
||||
self.account.stateManager.addUpdates(updates)
|
||||
for update in updates.allUpdates {
|
||||
if case let .updateMessageID(id, randomIdValue) = update {
|
||||
if case let .updateMessageID(updateMessageIDData) = update {
|
||||
let (id, randomIdValue) = (updateMessageIDData.id, updateMessageIDData.randomId)
|
||||
if randomIdValue == randomId {
|
||||
self.processedIds.insert(Int64(id))
|
||||
var state = self.state
|
||||
@@ -4413,10 +4455,10 @@ public final class GroupCallMessagesContext {
|
||||
flags: flags,
|
||||
call: self.reference.apiInputGroupCall,
|
||||
randomId: pendingSendStars.messageId,
|
||||
message: .textWithEntities(
|
||||
message: .textWithEntities(.init(
|
||||
text: "",
|
||||
entities: []
|
||||
),
|
||||
)),
|
||||
allowPaidStars: pendingSendStars.amount,
|
||||
sendAs: sendAs
|
||||
)) |> deliverOn(self.queue)).startStrict(next: { [weak self] updates in
|
||||
@@ -4425,7 +4467,8 @@ public final class GroupCallMessagesContext {
|
||||
}
|
||||
self.account.stateManager.addUpdates(updates)
|
||||
for update in updates.allUpdates {
|
||||
if case let .updateMessageID(id, randomIdValue) = update {
|
||||
if case let .updateMessageID(updateMessageIDData) = update {
|
||||
let (id, randomIdValue) = (updateMessageIDData.id, updateMessageIDData.randomId)
|
||||
if randomIdValue == pendingSendStars.messageId {
|
||||
self.processedIds.insert(Int64(id))
|
||||
var state = self.state
|
||||
|
||||
@@ -9,7 +9,7 @@ func _internal_rateCall(account: Account, callId: CallId, starsCount: Int32, com
|
||||
if userInitiated {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return account.network.request(Api.functions.phone.setCallRating(flags: flags, peer: Api.InputPhoneCall.inputPhoneCall(id: callId.id, accessHash: callId.accessHash), rating: starsCount, comment: comment))
|
||||
return account.network.request(Api.functions.phone.setCallRating(flags: flags, peer: Api.InputPhoneCall.inputPhoneCall(.init(id: callId.id, accessHash: callId.accessHash)), rating: starsCount, comment: comment))
|
||||
|> retryRequest
|
||||
|> map { _ in }
|
||||
}
|
||||
@@ -23,7 +23,7 @@ func _internal_saveCallDebugLog(network: Network, callId: CallId, log: String) -
|
||||
if log.count > 1024 * 16 {
|
||||
return .complete()
|
||||
}
|
||||
return network.request(Api.functions.phone.saveCallDebug(peer: Api.InputPhoneCall.inputPhoneCall(id: callId.id, accessHash: callId.accessHash), debug: .dataJSON(data: log)))
|
||||
return network.request(Api.functions.phone.saveCallDebug(peer: Api.InputPhoneCall.inputPhoneCall(.init(id: callId.id, accessHash: callId.accessHash)), debug: .dataJSON(.init(data: log))))
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
return .single(.boolTrue)
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func _internal_saveCompleteCallDebugLog(account: Account, callId: CallId, logPat
|
||||
case .progress:
|
||||
return .complete()
|
||||
case let .inputFile(inputFile):
|
||||
return account.network.request(Api.functions.phone.saveCallLog(peer: Api.InputPhoneCall.inputPhoneCall(id: callId.id, accessHash: callId.accessHash), file: inputFile))
|
||||
return account.network.request(Api.functions.phone.saveCallLog(peer: Api.InputPhoneCall.inputPhoneCall(.init(id: callId.id, accessHash: callId.accessHash)), file: inputFile))
|
||||
|> mapError { _ -> MultipartUploadError in
|
||||
return .generic
|
||||
}
|
||||
|
||||
@@ -158,13 +158,15 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func requestStreamState(dataSource: AudioBroadcastDataSource, callId: Int64, accessHash: Int64) -> Signal<EngineCallStreamState?, NoError> {
|
||||
return dataSource.download.request(Api.functions.phone.getGroupCallStreamChannels(call: .inputGroupCall(id: callId, accessHash: accessHash)))
|
||||
return dataSource.download.request(Api.functions.phone.getGroupCallStreamChannels(call: .inputGroupCall(.init(id: callId, accessHash: accessHash))))
|
||||
|> mapToSignal { result -> Signal<EngineCallStreamState?, MTRpcError> in
|
||||
switch result {
|
||||
case let .groupCallStreamChannels(channels):
|
||||
case let .groupCallStreamChannels(groupCallStreamChannelsData):
|
||||
let channels = groupCallStreamChannelsData.channels
|
||||
let state = EngineCallStreamState(channels: channels.map { channel -> EngineCallStreamState.Channel in
|
||||
switch channel {
|
||||
case let .groupCallStreamChannel(channel, scale, lastTimestampMs):
|
||||
case let .groupCallStreamChannel(groupCallStreamChannelData):
|
||||
let (channel, scale, lastTimestampMs) = (groupCallStreamChannelData.channel, groupCallStreamChannelData.scale, groupCallStreamChannelData.lastTimestampMs)
|
||||
return EngineCallStreamState.Channel(id: channel, scale: scale, latestTimestamp: lastTimestampMs)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -25,7 +25,8 @@ private func updatedRemoteContactPeers(network: Network, hash: Int64) -> Signal<
|
||||
switch result {
|
||||
case .contactsNotModified:
|
||||
return nil
|
||||
case let .contacts(_, savedCount, users):
|
||||
case let .contacts(contactsData):
|
||||
let (savedCount, users) = (contactsData.savedCount, contactsData.users)
|
||||
return (AccumulatedPeers(users: users), savedCount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ func _internal_importContact(account: Account, firstName: String, lastName: Stri
|
||||
var note: Api.TextWithEntities?
|
||||
if !noteText.isEmpty {
|
||||
flags |= (1 << 1)
|
||||
note = .textWithEntities(text: noteText, entities: apiEntitiesFromMessageTextEntities(noteEntities, associatedPeers: SimpleDictionary()))
|
||||
note = .textWithEntities(.init(text: noteText, entities: apiEntitiesFromMessageTextEntities(noteEntities, associatedPeers: SimpleDictionary())))
|
||||
}
|
||||
|
||||
let input = Api.InputContact.inputPhoneContact(flags: 0, clientId: 1, phone: phoneNumber, firstName: firstName, lastName: lastName, note: note)
|
||||
let input = Api.InputContact.inputPhoneContact(.init(flags: 0, clientId: 1, phone: phoneNumber, firstName: firstName, lastName: lastName, note: note))
|
||||
|
||||
return account.network.request(Api.functions.contacts.importContacts(contacts: [input]))
|
||||
|> map(Optional.init)
|
||||
@@ -24,7 +24,8 @@ func _internal_importContact(account: Account, firstName: String, lastName: Stri
|
||||
return account.postbox.transaction { transaction -> PeerId? in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .importedContacts(_, _, _, users):
|
||||
case let .importedContacts(importedContactsData):
|
||||
let users = importedContactsData.users
|
||||
if let first = users.first {
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
@@ -75,7 +76,7 @@ func _internal_addContactInteractively(account: Account, peerId: PeerId, firstNa
|
||||
var note: Api.TextWithEntities?
|
||||
if !noteText.isEmpty {
|
||||
flags |= (1 << 1)
|
||||
note = .textWithEntities(text: noteText, entities: apiEntitiesFromMessageTextEntities(noteEntities, associatedPeers: SimpleDictionary()))
|
||||
note = .textWithEntities(.init(text: noteText, entities: apiEntitiesFromMessageTextEntities(noteEntities, associatedPeers: SimpleDictionary())))
|
||||
}
|
||||
return account.network.request(Api.functions.contacts.addContact(flags: flags, id: inputUser, firstName: firstName, lastName: lastName, phone: phone, note: note))
|
||||
|> mapError { _ -> AddContactError in
|
||||
@@ -85,9 +86,11 @@ func _internal_addContactInteractively(account: Account, peerId: PeerId, firstNa
|
||||
return account.postbox.transaction { transaction -> Void in
|
||||
var peers = AccumulatedPeers()
|
||||
switch result {
|
||||
case let .updates(_, users, _, _, _):
|
||||
case let .updates(updatesData):
|
||||
let users = updatesData.users
|
||||
peers = AccumulatedPeers(users: users)
|
||||
case let .updatesCombined(_, users, _, _, _, _):
|
||||
case let .updatesCombined(updatesCombinedData):
|
||||
let users = updatesCombinedData.users
|
||||
peers = AccumulatedPeers(users: users)
|
||||
default:
|
||||
break
|
||||
|
||||
@@ -35,7 +35,7 @@ public enum UpdateContactNoteError {
|
||||
func _internal_updateContactNote(account: Account, peerId: PeerId, text: String, entities: [MessageTextEntity]) -> Signal<Never, UpdateContactNoteError> {
|
||||
return account.postbox.transaction { transaction -> Signal<Void, UpdateContactNoteError> in
|
||||
if let peer = transaction.getPeer(peerId) as? TelegramUser, let inputUser = apiInputUser(peer) {
|
||||
return account.network.request(Api.functions.contacts.updateContactNote(id: inputUser, note: .textWithEntities(text: text, entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary()))))
|
||||
return account.network.request(Api.functions.contacts.updateContactNote(id: inputUser, note: .textWithEntities(.init(text: text, entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary())))))
|
||||
|> mapError { _ -> UpdateContactNoteError in
|
||||
return .generic
|
||||
}
|
||||
|
||||
+9
-6
@@ -45,7 +45,8 @@ public extension TelegramEngine {
|
||||
}
|
||||
|> mapToSignal { result -> Signal<ParsedInfo, GetInfoError> in
|
||||
switch result {
|
||||
case let .historyImportParsed(flags, title):
|
||||
case let .historyImportParsed(historyImportParsedData):
|
||||
let (flags, title) = (historyImportParsedData.flags, historyImportParsedData.title)
|
||||
if (flags & (1 << 0)) != 0 {
|
||||
return .single(.privateChat(title: title))
|
||||
} else if (flags & (1 << 1)) != 0 {
|
||||
@@ -91,7 +92,8 @@ public extension TelegramEngine {
|
||||
}
|
||||
|> map { result -> Session in
|
||||
switch result {
|
||||
case let .historyImport(id):
|
||||
case let .historyImport(historyImportData):
|
||||
let id = historyImportData.id
|
||||
return Session(peerId: peerId, inputPeer: inputPeer, id: id)
|
||||
}
|
||||
}
|
||||
@@ -138,10 +140,10 @@ public extension TelegramEngine {
|
||||
case let .inputFile(inputFile):
|
||||
switch type {
|
||||
case .photo:
|
||||
inputMedia = .inputMediaUploadedPhoto(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil)
|
||||
inputMedia = .inputMediaUploadedPhoto(.init(flags: 0, file: inputFile, stickers: nil, ttlSeconds: nil))
|
||||
case .file, .video, .sticker, .voice:
|
||||
var attributes: [Api.DocumentAttribute] = []
|
||||
attributes.append(.documentAttributeFilename(fileName: fileName))
|
||||
attributes.append(.documentAttributeFilename(.init(fileName: fileName)))
|
||||
var resolvedMimeType = mimeType
|
||||
switch type {
|
||||
case .video:
|
||||
@@ -153,7 +155,7 @@ public extension TelegramEngine {
|
||||
default:
|
||||
break
|
||||
}
|
||||
inputMedia = .inputMediaUploadedDocument(flags: 0, file: inputFile, thumb: nil, mimeType: resolvedMimeType, attributes: attributes, stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil)
|
||||
inputMedia = .inputMediaUploadedDocument(.init(flags: 0, file: inputFile, thumb: nil, mimeType: resolvedMimeType, attributes: attributes, stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil))
|
||||
}
|
||||
case let .progress(value):
|
||||
return .single(value)
|
||||
@@ -245,7 +247,8 @@ public extension TelegramEngine {
|
||||
}
|
||||
|> map { result -> CheckPeerImportResult in
|
||||
switch result {
|
||||
case let .checkedHistoryImportPeer(confirmText):
|
||||
case let .checkedHistoryImportPeer(checkedHistoryImportPeerData):
|
||||
let confirmText = checkedHistoryImportPeerData.confirmText
|
||||
if confirmText.isEmpty {
|
||||
return .allowed
|
||||
} else {
|
||||
|
||||
@@ -106,7 +106,8 @@ func _internal_getCountriesList(accountManager: AccountManager<TelegramAccountMa
|
||||
|> retryRequest
|
||||
|> mapToSignal { result -> Signal<[Country], NoError> in
|
||||
switch result {
|
||||
case let .countriesList(apiCountries, hash):
|
||||
case let .countriesList(countriesListData):
|
||||
let (apiCountries, hash) = (countriesListData.countries, countriesListData.hash)
|
||||
let result = apiCountries.compactMap { Country(apiCountry: $0) }
|
||||
if result == current {
|
||||
return .complete()
|
||||
@@ -145,7 +146,8 @@ func _internal_getCountriesList(accountManager: AccountManager<TelegramAccountMa
|
||||
extension Country.CountryCode {
|
||||
init(apiCountryCode: Api.help.CountryCode) {
|
||||
switch apiCountryCode {
|
||||
case let .countryCode(_, countryCode, apiPrefixes, apiPatterns):
|
||||
case let .countryCode(countryCodeData):
|
||||
let (countryCode, apiPrefixes, apiPatterns) = (countryCodeData.countryCode, countryCodeData.prefixes, countryCodeData.patterns)
|
||||
let prefixes: [String] = apiPrefixes.flatMap { $0 } ?? []
|
||||
let patterns: [String] = apiPatterns.flatMap { $0 } ?? []
|
||||
self.init(code: countryCode, prefixes: prefixes, patterns: patterns)
|
||||
@@ -156,7 +158,8 @@ extension Country.CountryCode {
|
||||
extension Country {
|
||||
init(apiCountry: Api.help.Country) {
|
||||
switch apiCountry {
|
||||
case let .country(flags, iso2, defaultName, name, countryCodes):
|
||||
case let .country(countryData):
|
||||
let (flags, iso2, defaultName, name, countryCodes) = (countryData.flags, countryData.iso2, countryData.defaultName, countryData.name, countryData.countryCodes)
|
||||
self.init(id: iso2, name: defaultName, localizedName: name, countryCodes: countryCodes.map { Country.CountryCode(apiCountryCode: $0) }, hidden: (flags & 1 << 0) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ import TelegramApi
|
||||
extension LocalizationInfo {
|
||||
init(apiLanguage: Api.LangPackLanguage) {
|
||||
switch apiLanguage {
|
||||
case let .langPackLanguage(flags, name, nativeName, langCode, baseLangCode, pluralCode, stringsCount, translatedCount, translationsUrl):
|
||||
case let .langPackLanguage(langPackLanguageData):
|
||||
let (flags, name, nativeName, langCode, baseLangCode, pluralCode, stringsCount, translatedCount, translationsUrl) = (langPackLanguageData.flags, langPackLanguageData.name, langPackLanguageData.nativeName, langPackLanguageData.langCode, langPackLanguageData.baseLangCode, langPackLanguageData.pluralCode, langPackLanguageData.stringsCount, langPackLanguageData.translatedCount, langPackLanguageData.translationsUrl)
|
||||
self.init(languageCode: langCode, baseLanguageCode: baseLangCode, customPluralizationCode: pluralCode, title: name, localizedTitle: nativeName, isOfficial: (flags & (1 << 0)) != 0, totalStringCount: stringsCount, translatedStringCount: translatedCount, platformUrl: translationsUrl)
|
||||
}
|
||||
}
|
||||
@@ -24,3 +25,18 @@ public final class SuggestedLocalizationInfo {
|
||||
self.availableLocalizations = availableLocalizations
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Swiftgram
|
||||
// All the languages are "official" to prevent their deletion
|
||||
public let SGLocalizations: [LocalizationInfo] = [
|
||||
LocalizationInfo(languageCode: "zhcncc", baseLanguageCode: "zh-hans-raw", customPluralizationCode: "zh", title: "Chinese (Simplified) zhcncc", localizedTitle: "简体中文 (聪聪) - 已更完", isOfficial: true, totalStringCount: 7160, translatedStringCount: 7144, platformUrl: "https://translations.telegram.org/zhcncc/"),
|
||||
LocalizationInfo(languageCode: "taiwan", baseLanguageCode: "zh-hant-raw", customPluralizationCode: "zh", title: "Chinese (zh-Hant-TW) @zh_Hant_TW", localizedTitle: "正體中文", isOfficial: true, totalStringCount: 7160, translatedStringCount: 3761, platformUrl: "https://translations.telegram.org/taiwan/"),
|
||||
LocalizationInfo(languageCode: "hongkong", baseLanguageCode: "zh-hant-raw", customPluralizationCode: "zh", title: "Chinese (Hong Kong)", localizedTitle: "中文(香港)", isOfficial: true, totalStringCount: 7358, translatedStringCount: 6083, platformUrl: "https://translations.telegram.org/hongkong/"),
|
||||
// TODO(swiftgram): Japanese beta
|
||||
// baseLanguageCode is actually nil, since it's an "official" beta language
|
||||
LocalizationInfo(languageCode: "vi-raw", baseLanguageCode: "vi-raw", customPluralizationCode: "vi", title: "Vietnamese", localizedTitle: "Tiếng Việt (beta)", isOfficial: true, totalStringCount: 7160, translatedStringCount: 3795, platformUrl: "https://translations.telegram.org/vi/"),
|
||||
LocalizationInfo(languageCode: "hi-raw", baseLanguageCode: "hi-raw", customPluralizationCode: "hi", title: "Hindi", localizedTitle: "हिन्दी (beta)", isOfficial: true, totalStringCount: 7358, translatedStringCount: 992, platformUrl: "https://translations.telegram.org/hi/"),
|
||||
LocalizationInfo(languageCode: "ja-raw", baseLanguageCode: "ja-raw", customPluralizationCode: "ja", title: "Japanese", localizedTitle: "日本語 (beta)", isOfficial: true, totalStringCount: 9697, translatedStringCount: 9683, platformUrl: "https://translations.telegram.org/ja/"),
|
||||
// baseLanguageCode should be changed to nil? or hy?
|
||||
LocalizationInfo(languageCode: "earmenian", baseLanguageCode: "earmenian", customPluralizationCode: "hy", title: "Armenian", localizedTitle: "Հայերեն", isOfficial: true, totalStringCount: 7358, translatedStringCount: 6384, platformUrl: "https://translations.telegram.org/earmenian/")
|
||||
]
|
||||
|
||||
@@ -8,7 +8,8 @@ func _internal_currentlySuggestedLocalization(network: Network, extractKeys: [St
|
||||
|> retryRequest
|
||||
|> mapToSignal { result -> Signal<SuggestedLocalizationInfo?, NoError> in
|
||||
switch result {
|
||||
case let .config(_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, suggestedLangCode, _, _, _, _):
|
||||
case let .config(configData):
|
||||
let suggestedLangCode = configData.suggestedLangCode
|
||||
if let suggestedLangCode = suggestedLangCode {
|
||||
return _internal_suggestedLocalizationInfo(network: network, languageCode: suggestedLangCode, extractKeys: extractKeys) |> map(Optional.init)
|
||||
} else {
|
||||
@@ -25,11 +26,14 @@ func _internal_suggestedLocalizationInfo(network: Network, languageCode: String,
|
||||
var entries: [LocalizationEntry] = []
|
||||
for string in strings {
|
||||
switch string {
|
||||
case let .langPackString(key, value):
|
||||
case let .langPackString(langPackStringData):
|
||||
let (key, value) = (langPackStringData.key, langPackStringData.value)
|
||||
entries.append(.string(key: key, value: value))
|
||||
case let .langPackStringPluralized(_, key, zeroValue, oneValue, twoValue, fewValue, manyValue, otherValue):
|
||||
case let .langPackStringPluralized(langPackStringPluralizedData):
|
||||
let (key, zeroValue, oneValue, twoValue, fewValue, manyValue, otherValue) = (langPackStringPluralizedData.key, langPackStringPluralizedData.zeroValue, langPackStringPluralizedData.oneValue, langPackStringPluralizedData.twoValue, langPackStringPluralizedData.fewValue, langPackStringPluralizedData.manyValue, langPackStringPluralizedData.otherValue)
|
||||
entries.append(.pluralizedString(key: key, zero: zeroValue, one: oneValue, two: twoValue, few: fewValue, many: manyValue, other: otherValue))
|
||||
case let .langPackStringDeleted(key):
|
||||
case let .langPackStringDeleted(langPackStringDeletedData):
|
||||
let (key) = (langPackStringDeletedData.key)
|
||||
entries.append(.string(key: key, value: ""))
|
||||
}
|
||||
}
|
||||
@@ -78,15 +82,19 @@ func _internal_downloadLocalization(network: Network, languageCode: String) -> S
|
||||
let version: Int32
|
||||
var entries: [LocalizationEntry] = []
|
||||
switch result {
|
||||
case let .langPackDifference(_, _, versionValue, strings):
|
||||
case let .langPackDifference(langPackDifferenceData):
|
||||
let (versionValue, strings) = (langPackDifferenceData.version, langPackDifferenceData.strings)
|
||||
version = versionValue
|
||||
for string in strings {
|
||||
switch string {
|
||||
case let .langPackString(key, value):
|
||||
case let .langPackString(langPackStringData):
|
||||
let (key, value) = (langPackStringData.key, langPackStringData.value)
|
||||
entries.append(.string(key: key, value: value))
|
||||
case let .langPackStringPluralized(_, key, zeroValue, oneValue, twoValue, fewValue, manyValue, otherValue):
|
||||
case let .langPackStringPluralized(langPackStringPluralizedData):
|
||||
let (key, zeroValue, oneValue, twoValue, fewValue, manyValue, otherValue) = (langPackStringPluralizedData.key, langPackStringPluralizedData.zeroValue, langPackStringPluralizedData.oneValue, langPackStringPluralizedData.twoValue, langPackStringPluralizedData.fewValue, langPackStringPluralizedData.manyValue, langPackStringPluralizedData.otherValue)
|
||||
entries.append(.pluralizedString(key: key, zero: zeroValue, one: oneValue, two: twoValue, few: fewValue, many: manyValue, other: otherValue))
|
||||
case let .langPackStringDeleted(key):
|
||||
case let .langPackStringDeleted(langPackStringDeletedData):
|
||||
let (key) = (langPackStringDeletedData.key)
|
||||
entries.append(.string(key: key, value: ""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,12 +482,6 @@ private class AdMessagesHistoryContextImpl {
|
||||
}
|
||||
self.isActivated = true
|
||||
|
||||
// MISC: Block ads if setting enabled
|
||||
if MiscSettingsManager.shared.shouldBlockAds {
|
||||
self.stateValue = State(interPostInterval: nil, startDelay: nil, betweenDelay: nil, messages: [])
|
||||
return
|
||||
}
|
||||
|
||||
let peerId = self.peerId
|
||||
let accountPeerId = self.account.peerId
|
||||
let account = self.account
|
||||
@@ -516,7 +510,8 @@ private class AdMessagesHistoryContextImpl {
|
||||
|
||||
return account.postbox.transaction { transaction -> (interPostInterval: Int32?, startDelay: Int32?, betweenDelay: Int32?, messages: [Message]) in
|
||||
switch result {
|
||||
case let .sponsoredMessages(_, postsBetween, startDelay, betweenDelay, messages, chats, users):
|
||||
case let .sponsoredMessages(sponsoredMessagesData):
|
||||
let (postsBetween, startDelay, betweenDelay, messages, chats, users) = (sponsoredMessagesData.postsBetween, sponsoredMessagesData.startDelay, sponsoredMessagesData.betweenDelay, sponsoredMessagesData.messages, sponsoredMessagesData.chats, sponsoredMessagesData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -524,7 +519,8 @@ private class AdMessagesHistoryContextImpl {
|
||||
|
||||
for message in messages {
|
||||
switch message {
|
||||
case let .sponsoredMessage(flags, randomId, url, title, message, entities, photo, media, color, buttonText, sponsorInfo, additionalInfo, minDisplayDuration, maxDisplayDuration):
|
||||
case let .sponsoredMessage(sponsoredMessageData):
|
||||
let (flags, randomId, url, title, message, entities, apiPhoto, media, color, buttonText, sponsorInfo, additionalInfo, minDisplayDuration, maxDisplayDuration) = (sponsoredMessageData.flags, sponsoredMessageData.randomId, sponsoredMessageData.url, sponsoredMessageData.title, sponsoredMessageData.message, sponsoredMessageData.entities, sponsoredMessageData.photo, sponsoredMessageData.media, sponsoredMessageData.color, sponsoredMessageData.buttonText, sponsoredMessageData.sponsorInfo, sponsoredMessageData.additionalInfo, sponsoredMessageData.minDisplayDuration, sponsoredMessageData.maxDisplayDuration)
|
||||
var parsedEntities: [MessageTextEntity] = []
|
||||
if let entities = entities {
|
||||
parsedEntities = messageTextEntitiesFromApiEntities(entities)
|
||||
@@ -537,7 +533,8 @@ private class AdMessagesHistoryContextImpl {
|
||||
var backgroundEmojiId: Int64?
|
||||
if let color {
|
||||
switch color {
|
||||
case let .peerColor(_, color, backgroundEmojiIdValue):
|
||||
case let .peerColor(peerColorData):
|
||||
let (color, backgroundEmojiIdValue) = (peerColorData.color, peerColorData.backgroundEmojiId)
|
||||
nameColorIndex = color
|
||||
backgroundEmojiId = backgroundEmojiIdValue
|
||||
default:
|
||||
@@ -545,7 +542,7 @@ private class AdMessagesHistoryContextImpl {
|
||||
}
|
||||
}
|
||||
|
||||
let photo = photo.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let photo = apiPhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let contentMedia = textMediaAndExpirationTimerFromApiMedia(media, peerId).media
|
||||
|
||||
parsedMessages.append(CachedMessage(
|
||||
|
||||
+1
-2
@@ -64,7 +64,6 @@ func _internal_applyMaxReadIndexInteractively(transaction: Transaction, stateMan
|
||||
}
|
||||
}
|
||||
} else if index.id.peerId.namespace == Namespaces.Peer.CloudUser || index.id.peerId.namespace == Namespaces.Peer.CloudGroup || index.id.peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
// GHOST MODE: Don't send read receipts (blue checkmarks)
|
||||
if !GhostModeManager.shared.shouldHideReadReceipts {
|
||||
stateManager.notifyAppliedIncomingReadMessages([index.id])
|
||||
}
|
||||
@@ -167,7 +166,7 @@ func _internal_toggleForumThreadUnreadMarkInteractively(transaction: Transaction
|
||||
if peer.isForum {
|
||||
} else if peer.isMonoForum {
|
||||
if let inputPeer = apiInputPeer(peer), let subPeer = transaction.getPeer(PeerId(threadId)).flatMap(apiInputPeer) {
|
||||
let _ = network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: inputPeer, peer: .inputDialogPeer(peer: subPeer))).start()
|
||||
let _ = network.request(Api.functions.messages.markDialogUnread(flags: 1 << 0, parentPeer: inputPeer, peer: .inputDialogPeer(.init(peer: subPeer)))).start()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -298,17 +298,20 @@ func managedSynchronizeAttachMenuBots(accountPeerId: PeerId, postbox: Postbox, n
|
||||
}
|
||||
return postbox.transaction { transaction -> Void in
|
||||
switch result {
|
||||
case let .attachMenuBots(hash, bots, users):
|
||||
case let .attachMenuBots(attachMenuBotsData):
|
||||
let (hash, bots, users) = (attachMenuBotsData.hash, attachMenuBotsData.bots, attachMenuBotsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
var resultBots: [AttachMenuBots.Bot] = []
|
||||
for bot in bots {
|
||||
switch bot {
|
||||
case let .attachMenuBot(apiFlags, botId, name, apiPeerTypes, botIcons):
|
||||
case let .attachMenuBot(attachMenuBotData):
|
||||
let (apiFlags, botId, name, apiPeerTypes, botIcons) = (attachMenuBotData.flags, attachMenuBotData.botId, attachMenuBotData.shortName, attachMenuBotData.peerTypes, attachMenuBotData.icons)
|
||||
var icons: [AttachMenuBots.Bot.IconName: TelegramMediaFile] = [:]
|
||||
for icon in botIcons {
|
||||
switch icon {
|
||||
case let .attachMenuBotIcon(_, name, icon, _):
|
||||
case let .attachMenuBotIcon(attachMenuBotIconData):
|
||||
let (_, name, icon, _) = (attachMenuBotIconData.flags, attachMenuBotIconData.name, attachMenuBotIconData.icon, attachMenuBotIconData.colors)
|
||||
if let iconName = AttachMenuBots.Bot.IconName(string: name), let icon = telegramMediaFileFromApiDocument(icon, altDocuments: []) {
|
||||
icons[iconName] = icon
|
||||
}
|
||||
@@ -524,7 +527,8 @@ func _internal_getAttachMenuBot(accountPeerId: PeerId, postbox: Postbox, network
|
||||
|> mapToSignal { result -> Signal<AttachMenuBot, GetAttachMenuBotError> in
|
||||
return postbox.transaction { transaction -> Signal<AttachMenuBot, GetAttachMenuBotError> in
|
||||
switch result {
|
||||
case let .attachMenuBotsBot(bot, users):
|
||||
case let .attachMenuBotsBot(attachMenuBotsBotData):
|
||||
let (bot, users) = (attachMenuBotsBotData.bot, attachMenuBotsBotData.users)
|
||||
var peer: Peer?
|
||||
for user in users {
|
||||
let telegramUser = TelegramUser(user: user)
|
||||
@@ -539,11 +543,13 @@ func _internal_getAttachMenuBot(accountPeerId: PeerId, postbox: Postbox, network
|
||||
}
|
||||
|
||||
switch bot {
|
||||
case let .attachMenuBot(apiFlags, _, name, apiPeerTypes, botIcons):
|
||||
case let .attachMenuBot(attachMenuBotData):
|
||||
let (apiFlags, _, name, apiPeerTypes, botIcons) = (attachMenuBotData.flags, attachMenuBotData.botId, attachMenuBotData.shortName, attachMenuBotData.peerTypes, attachMenuBotData.icons)
|
||||
var icons: [AttachMenuBots.Bot.IconName: TelegramMediaFile] = [:]
|
||||
for icon in botIcons {
|
||||
switch icon {
|
||||
case let .attachMenuBotIcon(_, name, icon, _):
|
||||
case let .attachMenuBotIcon(attachMenuBotIconData):
|
||||
let (_, name, icon, _) = (attachMenuBotIconData.flags, attachMenuBotIconData.name, attachMenuBotIconData.icon, attachMenuBotIconData.colors)
|
||||
if let iconName = AttachMenuBots.Bot.IconName(string: name), let icon = telegramMediaFileFromApiDocument(icon, altDocuments: []) {
|
||||
icons[iconName] = icon
|
||||
}
|
||||
@@ -727,12 +733,12 @@ func _internal_getBotApp(account: Account, reference: BotAppReference) -> Signal
|
||||
let app: Api.InputBotApp
|
||||
switch reference {
|
||||
case let .id(id, accessHash):
|
||||
app = .inputBotAppID(id: id, accessHash: accessHash)
|
||||
app = .inputBotAppID(.init(id: id, accessHash: accessHash))
|
||||
case let .shortName(peerId, shortName):
|
||||
guard let bot = transaction.getPeer(peerId), let inputBot = apiInputUser(bot) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
app = .inputBotAppShortName(botId: inputBot, shortName: shortName)
|
||||
app = .inputBotAppShortName(.init(botId: inputBot, shortName: shortName))
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.messages.getBotApp(app: app, hash: 0))
|
||||
@@ -741,9 +747,11 @@ func _internal_getBotApp(account: Account, reference: BotAppReference) -> Signal
|
||||
}
|
||||
|> mapToSignal { result -> Signal<BotApp, GetBotAppError> in
|
||||
switch result {
|
||||
case let .botApp(botAppFlags, app):
|
||||
case let .botApp(botAppData):
|
||||
let (botAppFlags, app) = (botAppData.flags, botAppData.app)
|
||||
switch app {
|
||||
case let .botApp(flags, id, accessHash, shortName, title, description, photo, document, hash):
|
||||
case let .botApp(botAppData):
|
||||
let (flags, id, accessHash, shortName, title, description, photo, document, hash) = (botAppData.flags, botAppData.id, botAppData.accessHash, botAppData.shortName, botAppData.title, botAppData.description, botAppData.photo, botAppData.document, botAppData.hash)
|
||||
let _ = flags
|
||||
var appFlags = BotApp.Flags()
|
||||
if (botAppFlags & (1 << 0)) != 0 {
|
||||
@@ -769,7 +777,8 @@ func _internal_getBotApp(account: Account, reference: BotAppReference) -> Signal
|
||||
extension BotApp {
|
||||
convenience init?(apiBotApp: Api.BotApp) {
|
||||
switch apiBotApp {
|
||||
case let .botApp(_, id, accessHash, shortName, title, description, photo, document, hash):
|
||||
case let .botApp(botAppData):
|
||||
let (id, accessHash, shortName, title, description, photo, document, hash) = (botAppData.id, botAppData.accessHash, botAppData.shortName, botAppData.title, botAppData.description, botAppData.photo, botAppData.document, botAppData.hash)
|
||||
self.init(id: id, accessHash: accessHash, shortName: shortName, title: title, description: description, photo: telegramMediaImageFromApiPhoto(photo), document: document.flatMap { telegramMediaFileFromApiDocument($0, altDocuments: []) }, hash: hash, flags: [])
|
||||
case .botAppNotModified:
|
||||
return nil
|
||||
|
||||
@@ -19,7 +19,7 @@ public enum RequestSimpleWebViewSource : Equatable {
|
||||
func _internal_requestSimpleWebView(postbox: Postbox, network: Network, botId: PeerId, url: String?, source: RequestSimpleWebViewSource, themeParams: [String: Any]?) -> Signal<RequestWebViewResult, RequestWebViewError> {
|
||||
var serializedThemeParams: Api.DataJSON?
|
||||
if let themeParams = themeParams, let data = try? JSONSerialization.data(withJSONObject: themeParams, options: []), let dataString = String(data: data, encoding: .utf8) {
|
||||
serializedThemeParams = .dataJSON(data: dataString)
|
||||
serializedThemeParams = .dataJSON(.init(data: dataString))
|
||||
}
|
||||
return postbox.transaction { transaction -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
guard let bot = transaction.getPeer(botId), let inputUser = apiInputUser(bot) else {
|
||||
@@ -51,7 +51,8 @@ func _internal_requestSimpleWebView(postbox: Postbox, network: Network, botId: P
|
||||
}
|
||||
|> mapToSignal { result -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
switch result {
|
||||
case let .webViewResultUrl(flags, queryId, url):
|
||||
case let .webViewResultUrl(webViewResultUrlData):
|
||||
let (flags, queryId, url) = (webViewResultUrlData.flags, webViewResultUrlData.queryId, webViewResultUrlData.url)
|
||||
var resultFlags: RequestWebViewResult.Flags = []
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
resultFlags.insert(.fullSize)
|
||||
@@ -70,7 +71,7 @@ func _internal_requestSimpleWebView(postbox: Postbox, network: Network, botId: P
|
||||
func _internal_requestMainWebView(postbox: Postbox, network: Network, peerId: PeerId, botId: PeerId, source: RequestSimpleWebViewSource, themeParams: [String: Any]?) -> Signal<RequestWebViewResult, RequestWebViewError> {
|
||||
var serializedThemeParams: Api.DataJSON?
|
||||
if let themeParams = themeParams, let data = try? JSONSerialization.data(withJSONObject: themeParams, options: []), let dataString = String(data: data, encoding: .utf8) {
|
||||
serializedThemeParams = .dataJSON(data: dataString)
|
||||
serializedThemeParams = .dataJSON(.init(data: dataString))
|
||||
}
|
||||
return postbox.transaction { transaction -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
guard let bot = transaction.getPeer(botId), let inputUser = apiInputUser(bot) else {
|
||||
@@ -101,7 +102,8 @@ func _internal_requestMainWebView(postbox: Postbox, network: Network, peerId: Pe
|
||||
}
|
||||
|> mapToSignal { result -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
switch result {
|
||||
case let .webViewResultUrl(flags, queryId, url):
|
||||
case let .webViewResultUrl(webViewResultUrlData):
|
||||
let (flags, queryId, url) = (webViewResultUrlData.flags, webViewResultUrlData.queryId, webViewResultUrlData.url)
|
||||
var resultFlags: RequestWebViewResult.Flags = []
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
resultFlags.insert(.fullSize)
|
||||
@@ -160,7 +162,7 @@ private func keepWebViewSignal(network: Network, stateManager: AccountStateManag
|
||||
replyFlags |= 1 << 0
|
||||
topMsgId = Int32(clamping: threadId)
|
||||
}
|
||||
replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyToMessageId.id, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil)
|
||||
replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyToMessageId.id, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil))
|
||||
}
|
||||
let signal: Signal<Never, KeepWebViewError> = network.request(Api.functions.messages.prolongWebView(flags: flags, peer: peer, bot: bot, queryId: queryId, replyTo: replyTo, sendAs: sendAs))
|
||||
|> mapError { _ -> KeepWebViewError in
|
||||
@@ -204,7 +206,7 @@ private func keepWebViewSignal(network: Network, stateManager: AccountStateManag
|
||||
func _internal_requestWebView(postbox: Postbox, network: Network, stateManager: AccountStateManager, peerId: PeerId, botId: PeerId, url: String?, payload: String?, themeParams: [String: Any]?, fromMenu: Bool, replyToMessageId: MessageId?, threadId: Int64?) -> Signal<RequestWebViewResult, RequestWebViewError> {
|
||||
var serializedThemeParams: Api.DataJSON?
|
||||
if let themeParams = themeParams, let data = try? JSONSerialization.data(withJSONObject: themeParams, options: []), let dataString = String(data: data, encoding: .utf8) {
|
||||
serializedThemeParams = .dataJSON(data: dataString)
|
||||
serializedThemeParams = .dataJSON(.init(data: dataString))
|
||||
}
|
||||
|
||||
return postbox.transaction { transaction -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
@@ -248,9 +250,9 @@ func _internal_requestWebView(postbox: Postbox, network: Network, stateManager:
|
||||
} else if topMsgId != nil {
|
||||
replyFlags |= 1 << 0
|
||||
}
|
||||
replyTo = .inputReplyToMessage(flags: replyFlags, replyToMsgId: replyToMessageId.id, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil)
|
||||
replyTo = .inputReplyToMessage(.init(flags: replyFlags, replyToMsgId: replyToMessageId.id, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: monoforumPeerId, todoItemId: nil))
|
||||
} else if let monoforumPeerId {
|
||||
replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId)
|
||||
replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId))
|
||||
}
|
||||
|
||||
return network.request(Api.functions.messages.requestWebView(flags: flags, peer: inputPeer, bot: inputBot, url: url, startParam: payload, themeParams: serializedThemeParams, platform: botWebViewPlatform, replyTo: replyTo, sendAs: nil))
|
||||
@@ -259,7 +261,8 @@ func _internal_requestWebView(postbox: Postbox, network: Network, stateManager:
|
||||
}
|
||||
|> mapToSignal { result -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
switch result {
|
||||
case let .webViewResultUrl(webViewFlags, queryId, url):
|
||||
case let .webViewResultUrl(webViewResultUrlData):
|
||||
let (webViewFlags, queryId, url) = (webViewResultUrlData.flags, webViewResultUrlData.queryId, webViewResultUrlData.url)
|
||||
var resultFlags: RequestWebViewResult.Flags = []
|
||||
if (webViewFlags & (1 << 1)) != 0 {
|
||||
resultFlags.insert(.fullSize)
|
||||
@@ -273,7 +276,7 @@ func _internal_requestWebView(postbox: Postbox, network: Network, stateManager:
|
||||
} else {
|
||||
keepAlive = nil
|
||||
}
|
||||
|
||||
|
||||
return .single(RequestWebViewResult(flags: resultFlags, queryId: queryId, url: url, keepAliveSignal: keepAlive))
|
||||
}
|
||||
}
|
||||
@@ -309,7 +312,7 @@ func _internal_sendWebViewData(postbox: Postbox, network: Network, stateManager:
|
||||
func _internal_requestAppWebView(postbox: Postbox, network: Network, stateManager: AccountStateManager, peerId: PeerId, appReference: BotAppReference, payload: String?, themeParams: [String: Any]?, compact: Bool, fullscreen: Bool, allowWrite: Bool) -> Signal<RequestWebViewResult, RequestWebViewError> {
|
||||
var serializedThemeParams: Api.DataJSON?
|
||||
if let themeParams = themeParams, let data = try? JSONSerialization.data(withJSONObject: themeParams, options: []), let dataString = String(data: data, encoding: .utf8) {
|
||||
serializedThemeParams = .dataJSON(data: dataString)
|
||||
serializedThemeParams = .dataJSON(.init(data: dataString))
|
||||
}
|
||||
|
||||
return postbox.transaction { transaction -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
@@ -320,12 +323,12 @@ func _internal_requestAppWebView(postbox: Postbox, network: Network, stateManage
|
||||
let app: Api.InputBotApp
|
||||
switch appReference {
|
||||
case let .id(id, accessHash):
|
||||
app = .inputBotAppID(id: id, accessHash: accessHash)
|
||||
app = .inputBotAppID(.init(id: id, accessHash: accessHash))
|
||||
case let .shortName(peerId, shortName):
|
||||
guard let bot = transaction.getPeer(peerId), let inputBot = apiInputUser(bot) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
app = .inputBotAppShortName(botId: inputBot, shortName: shortName)
|
||||
app = .inputBotAppShortName(.init(botId: inputBot, shortName: shortName))
|
||||
}
|
||||
|
||||
var flags: Int32 = 0
|
||||
@@ -351,7 +354,8 @@ func _internal_requestAppWebView(postbox: Postbox, network: Network, stateManage
|
||||
}
|
||||
|> mapToSignal { result -> Signal<RequestWebViewResult, RequestWebViewError> in
|
||||
switch result {
|
||||
case let .webViewResultUrl(flags, queryId, url):
|
||||
case let .webViewResultUrl(webViewResultUrlData):
|
||||
let (flags, queryId, url) = (webViewResultUrlData.flags, webViewResultUrlData.queryId, webViewResultUrlData.url)
|
||||
var resultFlags: RequestWebViewResult.Flags = []
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
resultFlags.insert(.fullSize)
|
||||
@@ -415,7 +419,7 @@ public enum InvokeBotCustomMethodError {
|
||||
}
|
||||
|
||||
func _internal_invokeBotCustomMethod(postbox: Postbox, network: Network, botId: PeerId, method: String, params: String) -> Signal<String, InvokeBotCustomMethodError> {
|
||||
let params = Api.DataJSON.dataJSON(data: params)
|
||||
let params = Api.DataJSON.dataJSON(.init(data: params))
|
||||
return postbox.transaction { transaction -> Signal<String, InvokeBotCustomMethodError> in
|
||||
guard let bot = transaction.getPeer(botId), let inputUser = apiInputUser(bot) else {
|
||||
return .fail(.generic)
|
||||
@@ -425,7 +429,8 @@ func _internal_invokeBotCustomMethod(postbox: Postbox, network: Network, botId:
|
||||
return .generic
|
||||
}
|
||||
|> map { result -> String in
|
||||
if case let .dataJSON(data) = result {
|
||||
if case let .dataJSON(dataJSONData) = result {
|
||||
let data = dataJSONData.data
|
||||
return data
|
||||
} else {
|
||||
return ""
|
||||
@@ -1164,13 +1169,15 @@ fileprivate func _internal_requestConnectedStarRefBots(account: Account, id: En
|
||||
}
|
||||
return account.postbox.transaction { transaction -> (items: [EngineConnectedStarRefBotsContext.Item], totalCount: Int, nextOffset: (timestamp: Int32, link: String)?)? in
|
||||
switch result {
|
||||
case let .connectedStarRefBots(count, connectedBots, users):
|
||||
case let .connectedStarRefBots(connectedStarRefBotsData):
|
||||
let (count, connectedBots, users) = (connectedStarRefBotsData.count, connectedStarRefBotsData.connectedBots, connectedStarRefBotsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
var items: [EngineConnectedStarRefBotsContext.Item] = []
|
||||
for connectedBot in connectedBots {
|
||||
switch connectedBot {
|
||||
case let .connectedBotStarRef(_, url, date, botId, commissionPermille, durationMonths, participants, revenue):
|
||||
case let .connectedBotStarRef(connectedBotStarRefData):
|
||||
let (url, date, botId, commissionPermille, durationMonths, participants, revenue) = (connectedBotStarRefData.url, connectedBotStarRefData.date, connectedBotStarRefData.botId, connectedBotStarRefData.commissionPermille, connectedBotStarRefData.durationMonths, connectedBotStarRefData.participants, connectedBotStarRefData.revenue)
|
||||
guard let botPeer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId))) else {
|
||||
continue
|
||||
}
|
||||
@@ -1233,7 +1240,8 @@ fileprivate func _internal_requestSuggestedStarRefBots(account: Account, id: Eng
|
||||
}
|
||||
return account.postbox.transaction { transaction -> (items: [EngineSuggestedStarRefBotsContext.Item], totalCount: Int, nextOffset: String?)? in
|
||||
switch result {
|
||||
case let .suggestedStarRefBots(_, count, suggestedBots, users, nextOffset):
|
||||
case let .suggestedStarRefBots(suggestedStarRefBotsData):
|
||||
let (count, suggestedBots, users, nextOffset) = (suggestedStarRefBotsData.count, suggestedStarRefBotsData.suggestedBots, suggestedStarRefBotsData.users, suggestedStarRefBotsData.nextOffset)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
var items: [EngineSuggestedStarRefBotsContext.Item] = []
|
||||
@@ -1278,12 +1286,14 @@ func _internal_connectStarRefBot(account: Account, id: EnginePeer.Id, botId: Eng
|
||||
|> mapToSignal { result -> Signal<EngineConnectedStarRefBotsContext.Item, ConnectStarRefBotError> in
|
||||
return account.postbox.transaction { transaction -> EngineConnectedStarRefBotsContext.Item? in
|
||||
switch result {
|
||||
case let .connectedStarRefBots(_, connectedBots, users):
|
||||
case let .connectedStarRefBots(connectedStarRefBotsData):
|
||||
let (connectedBots, users) = (connectedStarRefBotsData.connectedBots, connectedStarRefBotsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
|
||||
if let bot = connectedBots.first {
|
||||
switch bot {
|
||||
case let .connectedBotStarRef(_, url, date, botId, commissionPermille, durationMonths, participants, revenue):
|
||||
case let .connectedBotStarRef(connectedBotStarRefData):
|
||||
let (url, date, botId, commissionPermille, durationMonths, participants, revenue) = (connectedBotStarRefData.url, connectedBotStarRefData.date, connectedBotStarRefData.botId, connectedBotStarRefData.commissionPermille, connectedBotStarRefData.durationMonths, connectedBotStarRefData.participants, connectedBotStarRefData.revenue)
|
||||
guard let botPeer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId))) else {
|
||||
return nil
|
||||
}
|
||||
@@ -1333,9 +1343,10 @@ fileprivate func _internal_removeConnectedStarRefBot(account: Account, id: Engin
|
||||
|> mapToSignal { result -> Signal<Never, ConnectStarRefBotError> in
|
||||
return account.postbox.transaction { transaction -> Void in
|
||||
switch result {
|
||||
case let .connectedStarRefBots(_, connectedBots, users):
|
||||
case let .connectedStarRefBots(connectedStarRefBotsData):
|
||||
let (connectedBots, users) = (connectedStarRefBotsData.connectedBots, connectedStarRefBotsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
|
||||
let _ = connectedBots
|
||||
}
|
||||
|
||||
@@ -1369,12 +1380,14 @@ func _internal_getStarRefBotConnection(account: Account, id: EnginePeer.Id, targ
|
||||
}
|
||||
return account.postbox.transaction { transaction -> EngineConnectedStarRefBotsContext.Item? in
|
||||
switch result {
|
||||
case let .connectedStarRefBots(_, connectedBots, users):
|
||||
case let .connectedStarRefBots(connectedStarRefBotsData):
|
||||
let (connectedBots, users) = (connectedStarRefBotsData.connectedBots, connectedStarRefBotsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
|
||||
if let bot = connectedBots.first {
|
||||
switch bot {
|
||||
case let .connectedBotStarRef(flags, url, date, botId, commissionPermille, durationMonths, participants, revenue):
|
||||
case let .connectedBotStarRef(connectedBotStarRefData):
|
||||
let (flags, url, date, botId, commissionPermille, durationMonths, participants, revenue) = (connectedBotStarRefData.flags, connectedBotStarRefData.url, connectedBotStarRefData.date, connectedBotStarRefData.botId, connectedBotStarRefData.commissionPermille, connectedBotStarRefData.durationMonths, connectedBotStarRefData.participants, connectedBotStarRefData.revenue)
|
||||
let isRevoked = (flags & (1 << 1)) != 0
|
||||
if isRevoked {
|
||||
return nil
|
||||
@@ -1431,9 +1444,19 @@ func _internal_getPossibleStarRefBotTargets(account: Account) -> Signal<[EngineP
|
||||
|
||||
if let apiChannels {
|
||||
switch apiChannels {
|
||||
case let .chats(chats), let .chatsSlice(_, chats):
|
||||
case let .chats(chatsData):
|
||||
let chats = chatsData.chats
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(chats: chats, users: []))
|
||||
|
||||
|
||||
for chat in chats {
|
||||
if let peer = transaction.getPeer(chat.peerId) {
|
||||
result.append(EnginePeer(peer))
|
||||
}
|
||||
}
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let chats = chatsSliceData.chats
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(chats: chats, users: []))
|
||||
|
||||
for chat in chats {
|
||||
if let peer = transaction.getPeer(chat.peerId) {
|
||||
result.append(EnginePeer(peer))
|
||||
|
||||
@@ -15,12 +15,14 @@ func _internal_clearCloudDraftsInteractively(postbox: Postbox, network: Network,
|
||||
}
|
||||
var keys = Set<Key>()
|
||||
switch updates {
|
||||
case let .updates(updates, users, chats, _, _):
|
||||
case let .updates(updatesData):
|
||||
let (updates, users, chats) = (updatesData.updates, updatesData.users, updatesData.chats)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
|
||||
for update in updates {
|
||||
switch update {
|
||||
case let .updateDraftMessage(_, peer, topMsgId, savedPeerId, _):
|
||||
case let .updateDraftMessage(updateDraftMessageData):
|
||||
let (peer, topMsgId, savedPeerId) = (updateDraftMessageData.peer, updateDraftMessageData.topMsgId, updateDraftMessageData.savedPeerId)
|
||||
var threadId: Int64?
|
||||
if let savedPeerId {
|
||||
threadId = savedPeerId.peerId.toInt64()
|
||||
@@ -55,10 +57,10 @@ func _internal_clearCloudDraftsInteractively(postbox: Postbox, network: Network,
|
||||
|
||||
var innerFlags: Int32 = 0
|
||||
innerFlags |= 1 << 0
|
||||
replyTo = .inputReplyToMessage(flags: innerFlags, replyToMsgId: 0, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil)
|
||||
replyTo = .inputReplyToMessage(.init(flags: innerFlags, replyToMsgId: 0, topMsgId: topMsgId, replyToPeerId: nil, quoteText: nil, quoteEntities: nil, quoteOffset: nil, monoforumPeerId: nil, todoItemId: nil))
|
||||
} else if let monoforumPeerId {
|
||||
flags |= (1 << 0)
|
||||
replyTo = .inputReplyToMonoForum(monoforumPeerId: monoforumPeerId)
|
||||
replyTo = .inputReplyToMonoForum(.init(monoforumPeerId: monoforumPeerId))
|
||||
}
|
||||
signals.append(network.request(Api.functions.messages.saveDraft(flags: flags, replyTo: replyTo, peer: inputPeer, message: "", entities: nil, media: nil, effect: nil, suggestedPost: nil))
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
|
||||
@@ -129,7 +129,8 @@ func _internal_clearCallHistory(account: Account, forEveryone: Bool) -> Signal<N
|
||||
|> mapToSignal { result -> Signal<Void, Bool> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .affectedFoundMessages(pts, ptsCount, offset, _):
|
||||
case let .affectedFoundMessages(affectedFoundMessagesData):
|
||||
let (pts, ptsCount, offset) = (affectedFoundMessagesData.pts, affectedFoundMessagesData.ptsCount, affectedFoundMessagesData.offset)
|
||||
account.stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)])
|
||||
if offset == 0 {
|
||||
return .fail(true)
|
||||
|
||||
+2
-1
@@ -219,7 +219,8 @@ func _internal_clearAuthorHistory(account: Account, peerId: PeerId, memberId: Pe
|
||||
|> mapToSignal { result -> Signal<Void, Bool> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .affectedHistory(pts, ptsCount, offset):
|
||||
case let .affectedHistory(affectedHistoryData):
|
||||
let (pts, ptsCount, offset) = (affectedHistoryData.pts, affectedHistoryData.ptsCount, affectedHistoryData.offset)
|
||||
account.stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)])
|
||||
if offset == 0 {
|
||||
return .fail(true)
|
||||
|
||||
+17
-9
@@ -465,17 +465,19 @@ public final class EngineStoryViewListContext {
|
||||
|> mapToSignal { result -> Signal<InternalState, NoError> in
|
||||
return account.postbox.transaction { transaction -> InternalState in
|
||||
switch result {
|
||||
case let .storyViewsList(_, count, viewsCount, forwardsCount, reactionsCount, views, chats, users, nextOffset):
|
||||
case let .storyViewsList(storyViewsListData):
|
||||
let (count, viewsCount, forwardsCount, reactionsCount, views, chats, users, nextOffset) = (storyViewsListData.count, storyViewsListData.viewsCount, storyViewsListData.forwardsCount, storyViewsListData.reactionsCount, storyViewsListData.views, storyViewsListData.chats, storyViewsListData.users, storyViewsListData.nextOffset)
|
||||
let peers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers)
|
||||
|
||||
var items: [Item] = []
|
||||
for view in views {
|
||||
switch view {
|
||||
case let .storyView(flags, userId, date, reaction):
|
||||
case let .storyView(storyViewData):
|
||||
let (flags, userId, date, reaction) = (storyViewData.flags, storyViewData.userId, storyViewData.date, storyViewData.reaction)
|
||||
let isBlocked = (flags & (1 << 0)) != 0
|
||||
let isBlockedFromStories = (flags & (1 << 1)) != 0
|
||||
|
||||
|
||||
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData in
|
||||
let previousData: CachedUserData
|
||||
@@ -511,7 +513,8 @@ public final class EngineStoryViewListContext {
|
||||
}
|
||||
)))
|
||||
}
|
||||
case let .storyViewPublicForward(flags, message):
|
||||
case let .storyViewPublicForward(storyViewPublicForwardData):
|
||||
let (flags, message) = (storyViewPublicForwardData.flags, storyViewPublicForwardData.message)
|
||||
let _ = flags
|
||||
if let storeMessage = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: false), let message = locallyRenderedMessage(message: storeMessage, peers: peers.peers) {
|
||||
items.append(.forward(Item.Forward(
|
||||
@@ -519,7 +522,8 @@ public final class EngineStoryViewListContext {
|
||||
storyStats: transaction.getPeerStoryStats(peerId: message.id.peerId)
|
||||
)))
|
||||
}
|
||||
case let .storyViewPublicRepost(flags, peerId, story):
|
||||
case let .storyViewPublicRepost(storyViewPublicRepostData):
|
||||
let (flags, peerId, story) = (storyViewPublicRepostData.flags, storyViewPublicRepostData.peerId, storyViewPublicRepostData.story)
|
||||
let _ = flags
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peer.id, transaction: transaction), case let .item(item) = storedItem, let media = item.media {
|
||||
@@ -685,14 +689,16 @@ public final class EngineStoryViewListContext {
|
||||
|> mapToSignal { result -> Signal<InternalState, NoError> in
|
||||
return account.postbox.transaction { transaction -> InternalState in
|
||||
switch result {
|
||||
case let .storyReactionsList(_, count, reactions, chats, users, nextOffset):
|
||||
case let .storyReactionsList(storyReactionsListData):
|
||||
let (count, reactions, chats, users, nextOffset) = (storyReactionsListData.count, storyReactionsListData.reactions, storyReactionsListData.chats, storyReactionsListData.users, storyReactionsListData.nextOffset)
|
||||
let peers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers)
|
||||
|
||||
var items: [Item] = []
|
||||
for reaction in reactions {
|
||||
switch reaction {
|
||||
case let .storyReaction(peerId, date, reaction):
|
||||
case let .storyReaction(storyReactionData):
|
||||
let (peerId, date, reaction) = (storyReactionData.peerId, storyReactionData.date, storyReactionData.reaction)
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
if let parsedReaction = MessageReaction.Reaction(apiReaction: reaction) {
|
||||
let reactionFile: TelegramMediaFile?
|
||||
@@ -713,14 +719,16 @@ public final class EngineStoryViewListContext {
|
||||
)))
|
||||
}
|
||||
}
|
||||
case let .storyReactionPublicForward(message):
|
||||
case let .storyReactionPublicForward(storyReactionPublicForwardData):
|
||||
let message = storyReactionPublicForwardData.message
|
||||
if let storeMessage = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: false), let message = locallyRenderedMessage(message: storeMessage, peers: peers.peers) {
|
||||
items.append(.forward(Item.Forward(
|
||||
message: EngineMessage(message),
|
||||
storyStats: transaction.getPeerStoryStats(peerId: message.id.peerId)
|
||||
)))
|
||||
}
|
||||
case let .storyReactionPublicRepost(peerId, story):
|
||||
case let .storyReactionPublicRepost(storyReactionPublicRepostData):
|
||||
let (peerId, story) = (storyReactionPublicRepostData.peerId, storyReactionPublicRepostData.story)
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peer.id, transaction: transaction), case let .item(item) = storedItem, let media = item.media {
|
||||
items.append(.repost(Item.Repost(
|
||||
|
||||
@@ -25,7 +25,8 @@ public func _internal_exportMessageLink(postbox: Postbox, network: Network, peer
|
||||
return network.request(Api.functions.channels.exportMessageLink(flags: flags, channel: input, id: sourceMessageId.id)) |> mapError { _ in return }
|
||||
|> map { res in
|
||||
switch res {
|
||||
case let .exportedMessageLink(link, _):
|
||||
case let .exportedMessageLink(exportedMessageLinkData):
|
||||
let (link, _) = (exportedMessageLinkData.link, exportedMessageLinkData.html)
|
||||
return link
|
||||
}
|
||||
} |> `catch` { _ -> Signal<String?, NoError> in
|
||||
|
||||
@@ -16,10 +16,10 @@ func _internal_editMessageFactCheck(account: Account, messageId: EngineMessage.I
|
||||
return account.network.request(Api.functions.messages.editFactCheck(
|
||||
peer: inputPeer,
|
||||
msgId: messageId.id,
|
||||
text: .textWithEntities(
|
||||
text: .textWithEntities(.init(
|
||||
text: text,
|
||||
entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary())
|
||||
)
|
||||
))
|
||||
))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.Updates?, NoError> in
|
||||
@@ -96,11 +96,13 @@ func _internal_getMessagesFactCheckByPeerId(account: Account, peerId: EnginePeer
|
||||
for result in results {
|
||||
let messageId = messageIds[index]
|
||||
switch result {
|
||||
case let .factCheck(_, country, text, hash):
|
||||
case let .factCheck(factCheckData):
|
||||
let (_, country, text, hash) = (factCheckData.flags, factCheckData.country, factCheckData.text, factCheckData.hash)
|
||||
let content: FactCheckMessageAttribute.Content
|
||||
if let text, let country {
|
||||
switch text {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
content = .Loaded(text: text, entities: messageTextEntitiesFromApiEntities(entities), country: country)
|
||||
}
|
||||
} else {
|
||||
|
||||
+8
-5
@@ -61,20 +61,23 @@ func _internal_getMessagesLoadIfNecessary(_ messageIds: [MessageId], postbox: Po
|
||||
if let peer = supportPeers[peerId] {
|
||||
var signal: Signal<Api.messages.Messages, MTRpcError>?
|
||||
if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup {
|
||||
signal = network.request(Api.functions.messages.getMessages(id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) })))
|
||||
signal = network.request(Api.functions.messages.getMessages(id: messageIds.map({ Api.InputMessage.inputMessageID(.init(id: $0.id)) })))
|
||||
} else if peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
if let inputChannel = apiInputChannel(peer) {
|
||||
signal = network.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) })))
|
||||
signal = network.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map({ Api.InputMessage.inputMessageID(.init(id: $0.id)) })))
|
||||
}
|
||||
}
|
||||
if let signal = signal {
|
||||
signals.append(signal |> map { result in
|
||||
switch result {
|
||||
case let .messages(messages, _, chats, users):
|
||||
case let .messages(messagesData):
|
||||
let (messages, _, chats, users) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users)
|
||||
return (peer, messages, chats, users)
|
||||
case let .messagesSlice(_, _, _, _, _, messages, _, chats, users):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (_, _, _, _, _, messages, _, chats, users) = (messagesSliceData.flags, messagesSliceData.count, messagesSliceData.nextRate, messagesSliceData.offsetIdOffset, messagesSliceData.searchFlood, messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users)
|
||||
return (peer, messages, chats, users)
|
||||
case let .channelMessages(_, _, _, _, messages, apiTopics, chats, users):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (_, _, _, _, messages, apiTopics, chats, users) = (channelMessagesData.flags, channelMessagesData.pts, channelMessagesData.count, channelMessagesData.offsetIdOffset, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users)
|
||||
let _ = apiTopics
|
||||
return (peer, messages, chats, users)
|
||||
case .messagesNotModified:
|
||||
|
||||
@@ -20,7 +20,8 @@ func _internal_markAllChatsAsRead(postbox: Postbox, network: Network, stateManag
|
||||
var signals: [Signal<Void, NoError>] = []
|
||||
for peer in result {
|
||||
switch peer {
|
||||
case let .dialogPeer(peer):
|
||||
case let .dialogPeer(dialogPeerData):
|
||||
let peer = dialogPeerData.peer
|
||||
let peerId = peer.peerId
|
||||
if peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
if let inputChannel = transaction.getPeer(peerId).flatMap(apiInputChannel) {
|
||||
@@ -42,7 +43,8 @@ func _internal_markAllChatsAsRead(postbox: Postbox, network: Network, stateManag
|
||||
|> mapToSignal { result -> Signal<Void, NoError> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .affectedMessages(pts, ptsCount):
|
||||
case let .affectedMessages(affectedMessagesData):
|
||||
let (pts, ptsCount) = (affectedMessagesData.pts, affectedMessagesData.ptsCount)
|
||||
stateManager.addUpdateGroups([.updatePts(pts: pts, ptsCount: ptsCount)])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ func _internal_messageReadStats(account: Account, id: MessageId) -> Signal<Messa
|
||||
return MessageReadStats(reactionCount: 0, peers: [], readTimestamps: [:])
|
||||
}
|
||||
switch result {
|
||||
case let .outboxReadDate(date):
|
||||
case let .outboxReadDate(outboxReadDateData):
|
||||
let date = outboxReadDateData.date
|
||||
return MessageReadStats(reactionCount: 0, peers: [EnginePeer(peer)], readTimestamps: [peer.id: date])
|
||||
}
|
||||
}
|
||||
@@ -47,7 +48,8 @@ func _internal_messageReadStats(account: Account, id: MessageId) -> Signal<Messa
|
||||
var items: [(Int64, Int32)] = []
|
||||
for item in result {
|
||||
switch item {
|
||||
case let .readParticipantDate(userId, date):
|
||||
case let .readParticipantDate(readParticipantDateData):
|
||||
let (userId, date) = (readParticipantDateData.userId, readParticipantDateData.date)
|
||||
items.append((userId, date))
|
||||
}
|
||||
}
|
||||
@@ -60,7 +62,8 @@ func _internal_messageReadStats(account: Account, id: MessageId) -> Signal<Messa
|
||||
let reactionCount: Signal<Int, NoError> = account.network.request(Api.functions.messages.getMessageReactionsList(flags: 0, peer: inputPeer, id: id.id, reaction: nil, offset: nil, limit: 1))
|
||||
|> map { result -> Int in
|
||||
switch result {
|
||||
case let .messageReactionsList(_, count, _, _, _, _):
|
||||
case let .messageReactionsList(messageReactionsListData):
|
||||
let count = messageReactionsListData.count
|
||||
return Int(count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,15 +23,18 @@ func _internal_requestMessageSelectPollOption(account: Account, messageId: Messa
|
||||
return account.postbox.transaction { transaction -> TelegramMediaPoll? in
|
||||
var resultPoll: TelegramMediaPoll?
|
||||
switch result {
|
||||
case let .updates(updates, _, _, _, _):
|
||||
case let .updates(updatesData):
|
||||
let updates = updatesData.updates
|
||||
for update in updates {
|
||||
switch update {
|
||||
case let .updateMessagePoll(_, id, poll, results):
|
||||
case let .updateMessagePoll(updateMessagePollData):
|
||||
let (id, poll, results) = (updateMessagePollData.pollId, updateMessagePollData.poll, updateMessagePollData.results)
|
||||
let pollId = MediaId(namespace: Namespaces.Media.CloudPoll, id: id)
|
||||
resultPoll = transaction.getMedia(pollId) as? TelegramMediaPoll
|
||||
if let poll = poll {
|
||||
switch poll {
|
||||
case let .poll(_, flags, question, answers, closePeriod, _):
|
||||
case let .poll(pollData):
|
||||
let (flags, question, answers, closePeriod) = (pollData.flags, pollData.question, pollData.answers, pollData.closePeriod)
|
||||
let publicity: TelegramMediaPollPublicity
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
publicity = .public
|
||||
@@ -47,7 +50,8 @@ func _internal_requestMessageSelectPollOption(account: Account, messageId: Messa
|
||||
let questionText: String
|
||||
let questionEntities: [MessageTextEntity]
|
||||
switch question {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
questionText = text
|
||||
questionEntities = messageTextEntitiesFromApiEntities(entities)
|
||||
}
|
||||
@@ -57,7 +61,8 @@ func _internal_requestMessageSelectPollOption(account: Account, messageId: Messa
|
||||
|
||||
let resultsMin: Bool
|
||||
switch results {
|
||||
case let .pollResults(flags, _, _, _, _, _):
|
||||
case let .pollResults(pollResultsData):
|
||||
let flags = pollResultsData.flags
|
||||
resultsMin = (flags & (1 << 0)) != 0
|
||||
}
|
||||
resultPoll = resultPoll?.withUpdatedResults(TelegramMediaPollResults(apiResults: results), min: resultsMin)
|
||||
@@ -142,7 +147,7 @@ func _internal_requestClosePoll(postbox: Postbox, network: Network, stateManager
|
||||
pollMediaFlags |= 1 << 1
|
||||
}
|
||||
|
||||
return network.request(Api.functions.messages.editMessage(flags: flags, peer: inputPeer, id: messageId.id, message: nil, media: .inputMediaPoll(flags: pollMediaFlags, poll: .poll(id: poll.pollId.id, flags: pollFlags, question: .textWithEntities(text: poll.text, entities: apiEntitiesFromMessageTextEntities(poll.textEntities, associatedPeers: SimpleDictionary())), answers: poll.options.map({ $0.apiOption }), closePeriod: poll.deadlineTimeout, closeDate: nil), correctAnswers: correctAnswers, solution: mappedSolution, solutionEntities: mappedSolutionEntities), replyMarkup: nil, entities: nil, scheduleDate: nil, scheduleRepeatPeriod: nil, quickReplyShortcutId: nil))
|
||||
return network.request(Api.functions.messages.editMessage(flags: flags, peer: inputPeer, id: messageId.id, message: nil, media: .inputMediaPoll(.init(flags: pollMediaFlags, poll: .poll(.init(id: poll.pollId.id, flags: pollFlags, question: .textWithEntities(.init(text: poll.text, entities: apiEntitiesFromMessageTextEntities(poll.textEntities, associatedPeers: SimpleDictionary()))), answers: poll.options.map({ $0.apiOption }), closePeriod: poll.deadlineTimeout, closeDate: nil)), correctAnswers: correctAnswers, solution: mappedSolution, solutionEntities: mappedSolutionEntities)), replyMarkup: nil, entities: nil, scheduleDate: nil, scheduleRepeatPeriod: nil, quickReplyShortcutId: nil))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.Updates?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -280,18 +285,22 @@ private final class PollResultsOptionContext {
|
||||
return ([], 0, nil)
|
||||
}
|
||||
switch result {
|
||||
case let .votesList(_, count, votes, chats, users, nextOffset):
|
||||
case let .votesList(votesListData):
|
||||
let (count, votes, chats, users, nextOffset) = (votesListData.count, votesListData.votes, votesListData.chats, votesListData.users, votesListData.nextOffset)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
var resultPeers: [RenderedPeer] = []
|
||||
for vote in votes {
|
||||
let peerId: PeerId
|
||||
switch vote {
|
||||
case let .messagePeerVote(peerIdValue, _, _):
|
||||
case let .messagePeerVote(messagePeerVoteData):
|
||||
let peerIdValue = messagePeerVoteData.peer
|
||||
peerId = peerIdValue.peerId
|
||||
case let .messagePeerVoteInputOption(peerIdValue, _):
|
||||
case let .messagePeerVoteInputOption(messagePeerVoteInputOptionData):
|
||||
let peerIdValue = messagePeerVoteInputOptionData.peer
|
||||
peerId = peerIdValue.peerId
|
||||
case let .messagePeerVoteMultiple(peerIdValue, _, _):
|
||||
case let .messagePeerVoteMultiple(messagePeerVoteMultipleData):
|
||||
let peerIdValue = messagePeerVoteMultipleData.peer
|
||||
peerId = peerIdValue.peerId
|
||||
}
|
||||
if let peer = transaction.getPeer(peerId) {
|
||||
|
||||
+2
-1
@@ -30,7 +30,8 @@ func _internal_getPreparedInlineMessage(account: Account, botId: EnginePeer.Id,
|
||||
}
|
||||
return account.postbox.transaction { transaction -> PreparedInlineMessage? in
|
||||
switch result {
|
||||
case let .preparedInlineMessage(queryId, result, apiPeerTypes, cacheTime, users):
|
||||
case let .preparedInlineMessage(preparedInlineMessageData):
|
||||
let (queryId, result, apiPeerTypes, cacheTime, users) = (preparedInlineMessageData.queryId, preparedInlineMessageData.result, preparedInlineMessageData.peerTypes, preparedInlineMessageData.cacheTime, preparedInlineMessageData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: AccumulatedPeers(users: users))
|
||||
let _ = cacheTime
|
||||
return PreparedInlineMessage(
|
||||
|
||||
@@ -152,7 +152,8 @@ func _internal_keepShortcutMessagesUpdated(account: Account) -> Signal<Never, No
|
||||
return account.postbox.transaction { transaction in
|
||||
var state = transaction.getPreferencesEntry(key: PreferencesKeys.shortcutMessages())?.get(QuickReplyMessageShortcutsState.self) ?? QuickReplyMessageShortcutsState(shortcuts: [])
|
||||
switch result {
|
||||
case let .quickReplies(quickReplies, messages, chats, users):
|
||||
case let .quickReplies(quickRepliesData):
|
||||
let (quickReplies, messages, chats, users) = (quickRepliesData.quickReplies, quickRepliesData.messages, quickRepliesData.chats, quickRepliesData.users)
|
||||
let previousShortcuts = state.shortcuts
|
||||
state.shortcuts.removeAll()
|
||||
|
||||
@@ -171,7 +172,8 @@ func _internal_keepShortcutMessagesUpdated(account: Account) -> Signal<Never, No
|
||||
|
||||
for quickReply in quickReplies {
|
||||
switch quickReply {
|
||||
case let .quickReply(shortcutId, shortcut, topMessage, _):
|
||||
case let .quickReply(quickReplyData):
|
||||
let (shortcutId, shortcut, topMessage, _) = (quickReplyData.shortcutId, quickReplyData.shortcut, quickReplyData.topMessage, quickReplyData.count)
|
||||
state.shortcuts.append(QuickReplyMessageShortcut(
|
||||
id: shortcutId,
|
||||
shortcut: shortcut
|
||||
@@ -543,7 +545,8 @@ public final class TelegramBusinessGreetingMessage: Codable, Equatable {
|
||||
extension TelegramBusinessGreetingMessage {
|
||||
convenience init(apiGreetingMessage: Api.BusinessGreetingMessage) {
|
||||
switch apiGreetingMessage {
|
||||
case let .businessGreetingMessage(shortcutId, recipients, noActivityDays):
|
||||
case let .businessGreetingMessage(businessGreetingMessageData):
|
||||
let (shortcutId, recipients, noActivityDays) = (businessGreetingMessageData.shortcutId, businessGreetingMessageData.recipients, businessGreetingMessageData.noActivityDays)
|
||||
self.init(
|
||||
shortcutId: shortcutId,
|
||||
recipients: TelegramBusinessRecipients(apiValue: recipients),
|
||||
@@ -715,14 +718,16 @@ public final class TelegramBusinessIntro: Codable, Equatable {
|
||||
extension TelegramBusinessAwayMessage {
|
||||
convenience init(apiAwayMessage: Api.BusinessAwayMessage) {
|
||||
switch apiAwayMessage {
|
||||
case let .businessAwayMessage(flags, shortcutId, schedule, recipients):
|
||||
case let .businessAwayMessage(businessAwayMessageData):
|
||||
let (flags, shortcutId, schedule, recipients) = (businessAwayMessageData.flags, businessAwayMessageData.shortcutId, businessAwayMessageData.schedule, businessAwayMessageData.recipients)
|
||||
let mappedSchedule: Schedule
|
||||
switch schedule {
|
||||
case .businessAwayMessageScheduleAlways:
|
||||
mappedSchedule = .always
|
||||
case .businessAwayMessageScheduleOutsideWorkHours:
|
||||
mappedSchedule = .outsideWorkingHours
|
||||
case let .businessAwayMessageScheduleCustom(startDate, endDate):
|
||||
case let .businessAwayMessageScheduleCustom(businessAwayMessageScheduleCustomData):
|
||||
let (startDate, endDate) = (businessAwayMessageScheduleCustomData.startDate, businessAwayMessageScheduleCustomData.endDate)
|
||||
mappedSchedule = .custom(beginTimestamp: startDate, endTimestamp: endDate)
|
||||
}
|
||||
|
||||
@@ -741,7 +746,9 @@ extension TelegramBusinessAwayMessage {
|
||||
extension TelegramBusinessIntro {
|
||||
convenience init(apiBusinessIntro: Api.BusinessIntro) {
|
||||
switch apiBusinessIntro {
|
||||
case let .businessIntro(_, title, description, sticker):
|
||||
case let .businessIntro(businessIntroData):
|
||||
let (flags, title, description, sticker) = (businessIntroData.flags, businessIntroData.title, businessIntroData.description, businessIntroData.sticker)
|
||||
let _ = flags
|
||||
self.init(title: title, text: description, stickerFile: sticker.flatMap { telegramMediaFileFromApiDocument($0, altDocuments: []) })
|
||||
}
|
||||
}
|
||||
@@ -752,15 +759,15 @@ extension TelegramBusinessIntro {
|
||||
if let stickerFile = self.stickerFile {
|
||||
if let fileResource = stickerFile.resource as? CloudDocumentMediaResource, let resource = stickerFile.resource as? TelegramCloudMediaResourceWithFileReference, let reference = resource.fileReference {
|
||||
flags |= 1 << 0
|
||||
sticker = .inputDocument(id: fileResource.fileId, accessHash: fileResource.accessHash, fileReference: Buffer(data: reference))
|
||||
sticker = .inputDocument(.init(id: fileResource.fileId, accessHash: fileResource.accessHash, fileReference: Buffer(data: reference)))
|
||||
}
|
||||
}
|
||||
return .inputBusinessIntro(
|
||||
return .inputBusinessIntro(.init(
|
||||
flags: flags,
|
||||
title: self.title,
|
||||
description: self.text,
|
||||
sticker: sticker
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -768,7 +775,8 @@ extension TelegramBusinessBotRights {
|
||||
init(apiValue: Api.BusinessBotRights) {
|
||||
var value: TelegramBusinessBotRights = []
|
||||
switch apiValue {
|
||||
case let .businessBotRights(flags):
|
||||
case let .businessBotRights(businessBotRightsData):
|
||||
let flags = businessBotRightsData.flags
|
||||
if (flags & (1 << 0)) != 0 {
|
||||
value.insert(.reply)
|
||||
}
|
||||
@@ -820,7 +828,8 @@ extension TelegramBusinessBotRights {
|
||||
extension TelegramBusinessRecipients {
|
||||
convenience init(apiValue: Api.BusinessRecipients) {
|
||||
switch apiValue {
|
||||
case let .businessRecipients(flags, users):
|
||||
case let .businessRecipients(businessRecipientsData):
|
||||
let (flags, users) = (businessRecipientsData.flags, businessRecipientsData.users)
|
||||
var categories: Categories = []
|
||||
if (flags & (1 << 0)) != 0 {
|
||||
categories.insert(.existingChats)
|
||||
@@ -846,7 +855,8 @@ extension TelegramBusinessRecipients {
|
||||
|
||||
convenience init(apiValue: Api.BusinessBotRecipients) {
|
||||
switch apiValue {
|
||||
case let .businessBotRecipients(flags, users, excludeUsers):
|
||||
case let .businessBotRecipients(businessBotRecipientsData):
|
||||
let (flags, users, excludeUsers) = (businessBotRecipientsData.flags, businessBotRecipientsData.users, businessBotRecipientsData.excludeUsers)
|
||||
var categories: Categories = []
|
||||
if (flags & (1 << 0)) != 0 {
|
||||
categories.insert(.existingChats)
|
||||
@@ -897,7 +907,7 @@ extension TelegramBusinessRecipients {
|
||||
flags |= 1 << 4
|
||||
}
|
||||
|
||||
return .inputBusinessRecipients(flags: flags, users: users)
|
||||
return .inputBusinessRecipients(.init(flags: flags, users: users))
|
||||
}
|
||||
|
||||
func apiInputBotValue(additionalPeers: [Peer], excludePeers: [Peer]) -> Api.InputBusinessBotRecipients {
|
||||
@@ -934,7 +944,7 @@ extension TelegramBusinessRecipients {
|
||||
flags |= 1 << 6
|
||||
}
|
||||
|
||||
return .inputBusinessBotRecipients(flags: flags, users: users, excludeUsers: excludeUsers)
|
||||
return .inputBusinessBotRecipients(.init(flags: flags, users: users, excludeUsers: excludeUsers))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -948,11 +958,11 @@ func _internal_updateBusinessGreetingMessage(account: Account, greetingMessage:
|
||||
|> mapToSignal { additionalPeers in
|
||||
var mappedMessage: Api.InputBusinessGreetingMessage?
|
||||
if let greetingMessage {
|
||||
mappedMessage = .inputBusinessGreetingMessage(
|
||||
mappedMessage = .inputBusinessGreetingMessage(.init(
|
||||
shortcutId: greetingMessage.shortcutId,
|
||||
recipients: greetingMessage.recipients.apiInputValue(additionalPeers: additionalPeers),
|
||||
noActivityDays: Int32(clamping: greetingMessage.inactivityDays)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
var flags: Int32 = 0
|
||||
@@ -997,7 +1007,7 @@ func _internal_updateBusinessAwayMessage(account: Account, awayMessage: Telegram
|
||||
case .outsideWorkingHours:
|
||||
mappedSchedule = .businessAwayMessageScheduleOutsideWorkHours
|
||||
case let .custom(beginTimestamp, endTimestamp):
|
||||
mappedSchedule = .businessAwayMessageScheduleCustom(startDate: beginTimestamp, endDate: endTimestamp)
|
||||
mappedSchedule = .businessAwayMessageScheduleCustom(Api.BusinessAwayMessageSchedule.Cons_businessAwayMessageScheduleCustom(startDate: beginTimestamp, endDate: endTimestamp))
|
||||
}
|
||||
|
||||
var flags: Int32 = 0
|
||||
@@ -1005,12 +1015,12 @@ func _internal_updateBusinessAwayMessage(account: Account, awayMessage: Telegram
|
||||
flags |= 1 << 0
|
||||
}
|
||||
|
||||
mappedMessage = .inputBusinessAwayMessage(
|
||||
mappedMessage = .inputBusinessAwayMessage(.init(
|
||||
flags: flags,
|
||||
shortcutId: awayMessage.shortcutId,
|
||||
schedule: mappedSchedule,
|
||||
recipients: awayMessage.recipients.apiInputValue(additionalPeers: additionalPeers)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
var flags: Int32 = 0
|
||||
@@ -1169,7 +1179,7 @@ public func _internal_setAccountConnectedBot(account: Account, bot: TelegramAcco
|
||||
var flags: Int32 = 0
|
||||
var mappedRights: Api.BusinessBotRights?
|
||||
var mappedBot: Api.InputUser = .inputUserEmpty
|
||||
var mappedRecipients: Api.InputBusinessBotRecipients = .inputBusinessBotRecipients(flags: 0, users: nil, excludeUsers: nil)
|
||||
var mappedRecipients: Api.InputBusinessBotRecipients = .inputBusinessBotRecipients(.init(flags: 0, users: nil, excludeUsers: nil))
|
||||
|
||||
if let bot, let inputBotUser = botUser.flatMap(apiInputUser) {
|
||||
mappedBot = inputBotUser
|
||||
@@ -1219,7 +1229,7 @@ public func _internal_setAccountConnectedBot(account: Account, bot: TelegramAcco
|
||||
if bot.rights.contains(.manageStories) {
|
||||
rightsFlags |= (1 << 13)
|
||||
}
|
||||
mappedRights = .businessBotRights(flags: rightsFlags)
|
||||
mappedRights = .businessBotRights(Api.BusinessBotRights.Cons_businessBotRights(flags: rightsFlags))
|
||||
mappedRecipients = bot.recipients.apiInputBotValue(additionalPeers: additionalPeers, excludePeers: excludePeers)
|
||||
} else {
|
||||
flags |= 1 << 1
|
||||
|
||||
@@ -156,7 +156,8 @@ private class ReplyThreadHistoryContextImpl {
|
||||
|> mapToSignal { discussionMessage -> Signal<DiscussionMessage, FetchChannelReplyThreadMessageError> in
|
||||
return account.postbox.transaction { transaction -> Signal<DiscussionMessage, FetchChannelReplyThreadMessageError> in
|
||||
switch discussionMessage {
|
||||
case let .discussionMessage(_, messages, maxId, readInboxMaxId, readOutboxMaxId, unreadCount, chats, users):
|
||||
case let .discussionMessage(discussionMessageData):
|
||||
let (messages, maxId, readInboxMaxId, readOutboxMaxId, unreadCount, chats, users) = (discussionMessageData.messages, discussionMessageData.maxId, discussionMessageData.readInboxMaxId, discussionMessageData.readOutboxMaxId, discussionMessageData.unreadCount, discussionMessageData.chats, discussionMessageData.users)
|
||||
let parsedMessages = messages.compactMap { message -> StoreMessage? in
|
||||
StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForumOrMonoForum)
|
||||
}
|
||||
@@ -476,7 +477,8 @@ private class ReplyThreadHistoryContextImpl {
|
||||
let validateSignal = strongSelf.account.network.request(Api.functions.messages.getDiscussionMessage(peer: inputPeer, msgId: Int32(clamping: threadId)))
|
||||
|> map { result -> (MessageId?, Int) in
|
||||
switch result {
|
||||
case let .discussionMessage(_, _, _, readInboxMaxId, _, unreadCount, _, _):
|
||||
case let .discussionMessage(discussionMessageData):
|
||||
let (readInboxMaxId, unreadCount) = (discussionMessageData.readInboxMaxId, discussionMessageData.unreadCount)
|
||||
return (readInboxMaxId.flatMap({ MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }), Int(unreadCount))
|
||||
}
|
||||
}
|
||||
@@ -670,7 +672,8 @@ func _internal_fetchChannelReplyThreadMessage(account: Account, messageId: Messa
|
||||
}
|
||||
return account.postbox.transaction { transaction -> DiscussionMessage? in
|
||||
switch discussionMessage {
|
||||
case let .discussionMessage(_, messages, maxId, readInboxMaxId, readOutboxMaxId, unreadCount, chats, users):
|
||||
case let .discussionMessage(discussionMessageData):
|
||||
let (messages, maxId, readInboxMaxId, readOutboxMaxId, unreadCount, chats, users) = (discussionMessageData.messages, discussionMessageData.maxId, discussionMessageData.readInboxMaxId, discussionMessageData.readOutboxMaxId, discussionMessageData.unreadCount, discussionMessageData.chats, discussionMessageData.users)
|
||||
let parsedMessages = messages.compactMap { message -> StoreMessage? in
|
||||
StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForumOrMonoForum)
|
||||
}
|
||||
|
||||
@@ -29,10 +29,12 @@ func _internal_reportAdMessage(account: Account, opaqueId: Data, option: Data?)
|
||||
}
|
||||
|> map { result -> ReportAdMessageResult in
|
||||
switch result {
|
||||
case let .sponsoredMessageReportResultChooseOption(title, options):
|
||||
case let .sponsoredMessageReportResultChooseOption(sponsoredMessageReportResultChooseOptionData):
|
||||
let (title, options) = (sponsoredMessageReportResultChooseOptionData.title, sponsoredMessageReportResultChooseOptionData.options)
|
||||
return .options(title: title, options: options.map {
|
||||
switch $0 {
|
||||
case let .sponsoredMessageReportOption(text, option):
|
||||
case let .sponsoredMessageReportOption(sponsoredMessageReportOptionData):
|
||||
let (text, option) = (sponsoredMessageReportOptionData.text, sponsoredMessageReportOptionData.option)
|
||||
return ReportAdMessageResult.Option(text: text, option: option.makeData())
|
||||
}
|
||||
})
|
||||
|
||||
@@ -63,14 +63,17 @@ func _internal_reportContent(account: Account, subject: ReportContentSubject, op
|
||||
}
|
||||
|> map { result -> ReportContentResult in
|
||||
switch result {
|
||||
case let .reportResultChooseOption(title, options):
|
||||
case let .reportResultChooseOption(reportResultChooseOptionData):
|
||||
let (title, options) = (reportResultChooseOptionData.title, reportResultChooseOptionData.options)
|
||||
return .options(title: title, options: options.map {
|
||||
switch $0 {
|
||||
case let .messageReportOption(text, option):
|
||||
case let .messageReportOption(messageReportOptionData):
|
||||
let (text, option) = (messageReportOptionData.text, messageReportOptionData.option)
|
||||
return ReportContentResult.Option(text: text, option: option.makeData())
|
||||
}
|
||||
})
|
||||
case let .reportResultAddComment(flags, option):
|
||||
case let .reportResultAddComment(reportResultAddCommentData):
|
||||
let (flags, option) = (reportResultAddCommentData.flags, reportResultAddCommentData.option)
|
||||
return .addComment(optional: (flags & (1 << 0)) != 0, option: option.makeData())
|
||||
case .reportResultReported:
|
||||
return .reported
|
||||
|
||||
+7
-2
@@ -1,3 +1,4 @@
|
||||
import SGLogging
|
||||
import Foundation
|
||||
import Postbox
|
||||
import SwiftSignalKit
|
||||
@@ -52,7 +53,7 @@ public struct RequestChatContextResultsResult {
|
||||
}
|
||||
}
|
||||
|
||||
func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId: PeerId, query: String, location: Signal<(Double, Double)?, NoError> = .single(nil), offset: String, incompleteResults: Bool = false, staleCachedResults: Bool = false) -> Signal<RequestChatContextResultsResult?, RequestChatContextResultsError> {
|
||||
func _internal_requestChatContextResults(IQTP: Bool = false, account: Account, botId: PeerId, peerId: PeerId, query: String, location: Signal<(Double, Double)?, NoError> = .single(nil), offset: String, incompleteResults: Bool = false, staleCachedResults: Bool = false) -> Signal<RequestChatContextResultsResult?, RequestChatContextResultsError> {
|
||||
return account.postbox.transaction { transaction -> (bot: Peer, peer: Peer)? in
|
||||
if let bot = transaction.getPeer(botId), let peer = transaction.getPeer(peerId) {
|
||||
return (bot, peer)
|
||||
@@ -119,7 +120,7 @@ func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId
|
||||
if let (latitude, longitude) = location {
|
||||
flags |= (1 << 0)
|
||||
let geoPointFlags: Int32 = 0
|
||||
geoPoint = Api.InputGeoPoint.inputGeoPoint(flags: geoPointFlags, lat: latitude, long: longitude, accuracyRadius: nil)
|
||||
geoPoint = Api.InputGeoPoint.inputGeoPoint(.init(flags: geoPointFlags, lat: latitude, long: longitude, accuracyRadius: nil))
|
||||
}
|
||||
|
||||
var signal: Signal<RequestChatContextResultsResult?, RequestChatContextResultsError> = account.network.request(Api.functions.messages.getInlineBotResults(flags: flags, bot: inputBot, peer: inputPeer, geoPoint: geoPoint, query: query, offset: offset))
|
||||
@@ -127,6 +128,10 @@ func _internal_requestChatContextResults(account: Account, botId: PeerId, peerId
|
||||
return ChatContextResultCollection(apiResults: result, botId: bot.id, peerId: peerId, query: query, geoPoint: location)
|
||||
}
|
||||
|> mapError { error -> RequestChatContextResultsError in
|
||||
// MARK: Swiftgram
|
||||
if IQTP {
|
||||
SGLogger.shared.log("SGIQTP", "Error requesting inline results: \(error.errorDescription ?? "nil")")
|
||||
}
|
||||
if error.errorDescription == "BOT_INLINE_GEO_REQUIRED" {
|
||||
return .locationRequired
|
||||
} else {
|
||||
|
||||
+61
-16
@@ -104,7 +104,7 @@ func _internal_requestMessageActionCallback(account: Account, messageId: Message
|
||||
guard let kdfResult = passwordKDF(encryptionProvider: account.network.encryptionProvider, password: password, derivation: currentPasswordDerivation, srpSessionData: srpSessionData) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
return .single(.inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
return .single(.inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))))
|
||||
} else {
|
||||
return .fail(.twoStepAuthMissing)
|
||||
}
|
||||
@@ -146,7 +146,8 @@ func _internal_requestMessageActionCallback(account: Account, messageId: Message
|
||||
return .none
|
||||
}
|
||||
switch result {
|
||||
case let .botCallbackAnswer(flags, message, url, _):
|
||||
case let .botCallbackAnswer(botCallbackAnswerData):
|
||||
let (flags, message, url) = (botCallbackAnswerData.flags, botCallbackAnswerData.message, botCallbackAnswerData.url)
|
||||
if let message = message {
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
return .alert(message)
|
||||
@@ -168,9 +169,39 @@ func _internal_requestMessageActionCallback(account: Account, messageId: Message
|
||||
}
|
||||
|
||||
public enum MessageActionUrlAuthResult {
|
||||
public struct Flags: OptionSet {
|
||||
public var rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static let requestWriteAccess = Flags(rawValue: 1 << 0)
|
||||
public static let requestPhoneNumber = Flags(rawValue: 1 << 1)
|
||||
}
|
||||
|
||||
public struct ClientData : Equatable {
|
||||
public let browser: String
|
||||
public let platform: String
|
||||
public let ip: String
|
||||
public let region: String
|
||||
|
||||
public init(browser: String, platform: String, ip: String, region: String) {
|
||||
self.browser = browser
|
||||
self.platform = platform
|
||||
self.ip = ip
|
||||
self.region = region
|
||||
}
|
||||
}
|
||||
|
||||
case `default`
|
||||
case accepted(String)
|
||||
case request(String, Peer, Bool)
|
||||
case accepted(url: String?)
|
||||
case request(domain: String, bot: Peer, clientData: ClientData?, flags: Flags)
|
||||
}
|
||||
|
||||
public enum MessageActionUrlAuthError {
|
||||
case generic
|
||||
case urlExpired
|
||||
}
|
||||
|
||||
public enum MessageActionUrlSubject {
|
||||
@@ -212,19 +243,35 @@ func _internal_requestMessageActionUrlAuth(account: Account, subject: MessageAct
|
||||
switch result {
|
||||
case .urlAuthResultDefault:
|
||||
return .default
|
||||
case let .urlAuthResultAccepted(url):
|
||||
return .accepted(url)
|
||||
case let .urlAuthResultRequest(flags, bot, domain):
|
||||
return .request(domain, TelegramUser(user: bot), (flags & (1 << 0)) != 0)
|
||||
case let .urlAuthResultAccepted(urlAuthResultAcceptedData):
|
||||
let url = urlAuthResultAcceptedData.url
|
||||
return .accepted(url: url)
|
||||
case let .urlAuthResultRequest(urlAuthResultRequestData):
|
||||
let (apiFlags, bot, domain) = (urlAuthResultRequestData.flags, urlAuthResultRequestData.bot, urlAuthResultRequestData.domain)
|
||||
var clientData: MessageActionUrlAuthResult.ClientData?
|
||||
if let browser = urlAuthResultRequestData.browser, let platform = urlAuthResultRequestData.platform, let ip = urlAuthResultRequestData.ip, let region = urlAuthResultRequestData.region {
|
||||
clientData = MessageActionUrlAuthResult.ClientData(browser: browser, platform: platform, ip: ip, region: region)
|
||||
}
|
||||
var flags: MessageActionUrlAuthResult.Flags = []
|
||||
if (apiFlags & (1 << 0)) != 0 {
|
||||
flags.insert(.requestWriteAccess)
|
||||
}
|
||||
if (apiFlags & (1 << 1)) != 0 {
|
||||
flags.insert(.requestPhoneNumber)
|
||||
}
|
||||
return .request(domain: domain, bot: TelegramUser(user: bot), clientData: clientData, flags: flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _internal_acceptMessageActionUrlAuth(account: Account, subject: MessageActionUrlSubject, allowWriteAccess: Bool) -> Signal<MessageActionUrlAuthResult, NoError> {
|
||||
func _internal_acceptMessageActionUrlAuth(account: Account, subject: MessageActionUrlSubject, allowWriteAccess: Bool, sharePhoneNumber: Bool) -> Signal<MessageActionUrlAuthResult, MessageActionUrlAuthError> {
|
||||
var flags: Int32 = 0
|
||||
if allowWriteAccess {
|
||||
flags |= Int32(1 << 0)
|
||||
}
|
||||
if sharePhoneNumber {
|
||||
flags |= Int32(1 << 3)
|
||||
}
|
||||
|
||||
let request: Signal<Api.UrlAuthResult?, MTRpcError>
|
||||
switch subject {
|
||||
@@ -250,16 +297,14 @@ func _internal_acceptMessageActionUrlAuth(account: Account, subject: MessageActi
|
||||
|
||||
|
||||
return request
|
||||
|> `catch` { _ -> Signal<Api.UrlAuthResult?, NoError> in
|
||||
return .single(nil)
|
||||
|> mapError { _ -> MessageActionUrlAuthError in
|
||||
return .generic
|
||||
}
|
||||
|> map { result -> MessageActionUrlAuthResult in
|
||||
guard let result = result else {
|
||||
return .default
|
||||
}
|
||||
switch result {
|
||||
case let .urlAuthResultAccepted(url):
|
||||
return .accepted(url)
|
||||
case let .urlAuthResultAccepted(urlAuthResultAcceptedData):
|
||||
let url = urlAuthResultAcceptedData.url
|
||||
return .accepted(url: url)
|
||||
default:
|
||||
return .default
|
||||
}
|
||||
|
||||
@@ -88,26 +88,30 @@ private func mergedState(transaction: Transaction, seedConfiguration: SeedConfig
|
||||
let totalCount: Int32
|
||||
let nextRate: Int32?
|
||||
switch result {
|
||||
case let .channelMessages(_, _, count, _, apiMessages, apiTopics, apiChats, apiUsers):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (_, _, count, _, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.flags, channelMessagesData.pts, channelMessagesData.count, channelMessagesData.offsetIdOffset, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users)
|
||||
messages = apiMessages
|
||||
let _ = apiTopics
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
totalCount = count
|
||||
nextRate = nil
|
||||
case let .messages(apiMessages, _, apiChats, apiUsers):
|
||||
case let .messages(messagesData):
|
||||
let (apiMessages, _, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
totalCount = Int32(messages.count)
|
||||
nextRate = nil
|
||||
case let .messagesSlice(_, count, apiNextRate, _, _, apiMessages, _, apiChats, apiUsers):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (_, count, apiNextRate, _, _, apiMessages, _, apiChats, apiUsers) = (messagesSliceData.flags, messagesSliceData.count, messagesSliceData.nextRate, messagesSliceData.offsetIdOffset, messagesSliceData.searchFlood, messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
totalCount = count
|
||||
nextRate = apiNextRate
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
chats = []
|
||||
users = []
|
||||
@@ -282,13 +286,17 @@ func _internal_getSearchMessageCount(account: Account, location: SearchMessagesL
|
||||
return account.network.request(Api.functions.messages.search(flags: flags, peer: inputPeer, q: query, fromId: fromPeer, savedPeerId: savedPeerId, savedReaction: nil, topMsgId: topMsgId, filter: .inputMessagesFilterEmpty, minDate: 0, maxDate: 0, offsetId: 0, addOffset: 0, limit: 1, maxId: 0, minId: 0, hash: 0))
|
||||
|> map { result -> Int? in
|
||||
switch result {
|
||||
case let .channelMessages(_, _, count, _, _, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let count = channelMessagesData.count
|
||||
return Int(count)
|
||||
case let .messages(messages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let messages = messagesData.messages
|
||||
return messages.count
|
||||
case let .messagesNotModified(count):
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let count = messagesNotModifiedData.count
|
||||
return Int(count)
|
||||
case let .messagesSlice(_, count, _, _, _, _, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let count = messagesSliceData.count
|
||||
return Int(count)
|
||||
}
|
||||
}
|
||||
@@ -298,7 +306,7 @@ func _internal_getSearchMessageCount(account: Account, location: SearchMessagesL
|
||||
}
|
||||
}
|
||||
|
||||
func _internal_searchMessages(account: Account, location: SearchMessagesLocation, query: String, state: SearchMessagesState?, centerId: MessageId?, limit: Int32 = 100) -> Signal<(SearchMessagesResult, SearchMessagesState), NoError> {
|
||||
func _internal_searchMessages(account: Account, location: SearchMessagesLocation, query: String, state: SearchMessagesState?, centerId: MessageId?, limit: Int32 = 100, forceLocal: Bool = false) -> Signal<(SearchMessagesResult, SearchMessagesState), NoError> {
|
||||
if case let .peer(peerId, fromId, tags, reactions, threadId, minDate, maxDate) = location, fromId == nil, tags == nil, peerId == account.peerId, let reactions, let reaction = reactions.first, (minDate == nil || minDate == 0), (maxDate == nil || maxDate == 0) {
|
||||
return account.postbox.transaction { transaction -> (SearchMessagesResult, SearchMessagesState) in
|
||||
let messages = transaction.getMessagesWithCustomTag(peerId: peerId, namespace: Namespaces.Message.Cloud, threadId: threadId, customTag: ReactionsMessageAttribute.messageTag(reaction: reaction), from: MessageIndex.upperBound(peerId: peerId, namespace: Namespaces.Message.Cloud), includeFrom: false, to: MessageIndex.lowerBound(peerId: peerId, namespace: Namespaces.Message.Cloud), limit: 500)
|
||||
@@ -329,14 +337,31 @@ func _internal_searchMessages(account: Account, location: SearchMessagesLocation
|
||||
let remoteSearchResult: Signal<(Api.messages.Messages?, Api.messages.Messages?), NoError>
|
||||
switch location {
|
||||
case let .peer(peerId, fromId, tags, reactions, threadId, minDate, maxDate):
|
||||
if peerId.namespace == Namespaces.Peer.SecretChat {
|
||||
if peerId.namespace == Namespaces.Peer.SecretChat || forceLocal {
|
||||
return account.postbox.transaction { transaction -> (SearchMessagesResult, SearchMessagesState) in
|
||||
var readStates: [PeerId: CombinedPeerReadState] = [:]
|
||||
var threadInfo: [MessageId: MessageHistoryThreadData] = [:]
|
||||
if let readState = transaction.getCombinedPeerReadState(peerId) {
|
||||
readStates[peerId] = readState
|
||||
}
|
||||
let result = transaction.searchMessages(peerId: peerId, query: query, tags: tags)
|
||||
// MARK: Swiftgram
|
||||
var result: [Message] = []
|
||||
if forceLocal {
|
||||
transaction.withAllMessages(peerId: peerId, { message in
|
||||
if result.count >= limit {
|
||||
return false
|
||||
}
|
||||
if let tags = tags, message.tags != tags {
|
||||
return true
|
||||
}
|
||||
if message.text.contains(query) {
|
||||
result.append(message)
|
||||
}
|
||||
return true
|
||||
})
|
||||
} else {
|
||||
result = transaction.searchMessages(peerId: peerId, query: query, tags: tags)
|
||||
}
|
||||
|
||||
for message in result {
|
||||
for attribute in message.attributes {
|
||||
@@ -604,11 +629,13 @@ func _internal_searchMessages(account: Account, location: SearchMessagesLocation
|
||||
|
||||
if let result {
|
||||
switch result {
|
||||
case let .messagesSlice(_, _, _, _, searchFlood, _, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let searchFlood = messagesSliceData.searchFlood
|
||||
if let searchFlood {
|
||||
transaction.updatePreferencesEntry(key: PreferencesKeys.globalPostSearchState(), { _ in
|
||||
switch searchFlood {
|
||||
case let .searchPostsFlood(_, totalDaily, remains, waitTill, starsAmount):
|
||||
case let .searchPostsFlood(searchPostsFloodData):
|
||||
let (_, totalDaily, remains, waitTill, starsAmount) = (searchPostsFloodData.flags, searchPostsFloodData.totalDaily, searchPostsFloodData.remains, searchPostsFloodData.waitTill, searchPostsFloodData.starsAmount)
|
||||
return PreferencesEntry(TelegramGlobalPostSearchState(
|
||||
totalFreeSearches: totalDaily,
|
||||
remainingFreeSearches: remains,
|
||||
@@ -673,12 +700,12 @@ func _internal_downloadMessage(accountPeerId: PeerId, postbox: Postbox, network:
|
||||
let signal: Signal<Api.messages.Messages, MTRpcError>
|
||||
if messageId.peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
if let channel = apiInputChannel(peer) {
|
||||
signal = network.request(Api.functions.channels.getMessages(channel: channel, id: [Api.InputMessage.inputMessageID(id: messageId.id)]))
|
||||
signal = network.request(Api.functions.channels.getMessages(channel: channel, id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))]))
|
||||
} else {
|
||||
signal = .complete()
|
||||
}
|
||||
} else {
|
||||
signal = network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(id: messageId.id)]))
|
||||
signal = network.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(.init(id: messageId.id))]))
|
||||
}
|
||||
|
||||
return signal
|
||||
@@ -694,25 +721,29 @@ func _internal_downloadMessage(accountPeerId: PeerId, postbox: Postbox, network:
|
||||
let chats: [Api.Chat]
|
||||
let users: [Api.User]
|
||||
switch result {
|
||||
case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.flags, channelMessagesData.pts, channelMessagesData.count, channelMessagesData.offsetIdOffset, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users)
|
||||
messages = apiMessages
|
||||
let _ = apiTopics
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messages(apiMessages, _, apiChats, apiUsers):
|
||||
case let .messages(messagesData):
|
||||
let (apiMessages, _, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, apiChats, apiUsers):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (_, _, _, _, _, apiMessages, _, apiChats, apiUsers) = (messagesSliceData.flags, messagesSliceData.count, messagesSliceData.nextRate, messagesSliceData.offsetIdOffset, messagesSliceData.searchFlood, messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
chats = []
|
||||
users = []
|
||||
}
|
||||
|
||||
|
||||
let postboxSignal = postbox.transaction { transaction -> Message? in
|
||||
var peers: [PeerId: Peer] = [:]
|
||||
|
||||
@@ -762,12 +793,12 @@ func fetchRemoteMessage(accountPeerId: PeerId, postbox: Postbox, source: FetchMe
|
||||
}
|
||||
} else if id.peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
if let channel = peer.inputChannel {
|
||||
signal = source.request(Api.functions.channels.getMessages(channel: channel, id: [Api.InputMessage.inputMessageID(id: id.id)]))
|
||||
signal = source.request(Api.functions.channels.getMessages(channel: channel, id: [Api.InputMessage.inputMessageID(.init(id: id.id))]))
|
||||
} else {
|
||||
signal = .fail(MTRpcError(errorCode: 400, errorDescription: "Peer Not Found"))
|
||||
}
|
||||
} else if id.peerId.namespace == Namespaces.Peer.CloudUser || id.peerId.namespace == Namespaces.Peer.CloudGroup {
|
||||
signal = source.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(id: id.id)]))
|
||||
signal = source.request(Api.functions.messages.getMessages(id: [Api.InputMessage.inputMessageID(.init(id: id.id))]))
|
||||
} else {
|
||||
signal = .fail(MTRpcError(errorCode: 400, errorDescription: "Invalid Peer"))
|
||||
}
|
||||
@@ -785,25 +816,29 @@ func fetchRemoteMessage(accountPeerId: PeerId, postbox: Postbox, source: FetchMe
|
||||
let chats: [Api.Chat]
|
||||
let users: [Api.User]
|
||||
switch result {
|
||||
case let .channelMessages(_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (_, _, _, _, apiMessages, apiTopics, apiChats, apiUsers) = (channelMessagesData.flags, channelMessagesData.pts, channelMessagesData.count, channelMessagesData.offsetIdOffset, channelMessagesData.messages, channelMessagesData.topics, channelMessagesData.chats, channelMessagesData.users)
|
||||
messages = apiMessages
|
||||
let _ = apiTopics
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messages(apiMessages, _, apiChats, apiUsers):
|
||||
case let .messages(messagesData):
|
||||
let (apiMessages, _, apiChats, apiUsers) = (messagesData.messages, messagesData.topics, messagesData.chats, messagesData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, apiChats, apiUsers):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (_, _, _, _, _, apiMessages, _, apiChats, apiUsers) = (messagesSliceData.flags, messagesSliceData.count, messagesSliceData.nextRate, messagesSliceData.offsetIdOffset, messagesSliceData.searchFlood, messagesSliceData.messages, messagesSliceData.topics, messagesSliceData.chats, messagesSliceData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
chats = []
|
||||
users = []
|
||||
}
|
||||
|
||||
|
||||
return postbox.transaction { transaction -> Message? in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
@@ -856,13 +891,17 @@ func _internal_searchMessageIdByTimestamp(account: Account, peerId: PeerId, thre
|
||||
|> map { result -> MessageIndex? in
|
||||
let messages: [Api.Message]
|
||||
switch result {
|
||||
case let .messages(apiMessages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let apiMessages = messagesData.messages
|
||||
messages = apiMessages
|
||||
case let .channelMessages(_, _, _, _, apiMessages, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let apiMessages = channelMessagesData.messages
|
||||
messages = apiMessages
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let apiMessages = messagesSliceData.messages
|
||||
messages = apiMessages
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
}
|
||||
for message in messages {
|
||||
@@ -893,13 +932,17 @@ func _internal_searchMessageIdByTimestamp(account: Account, peerId: PeerId, thre
|
||||
|> map { result -> MessageIndex? in
|
||||
let messages: [Api.Message]
|
||||
switch result {
|
||||
case let .messages(apiMessages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let apiMessages = messagesData.messages
|
||||
messages = apiMessages
|
||||
case let .channelMessages(_, _, _, _, apiMessages, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let apiMessages = channelMessagesData.messages
|
||||
messages = apiMessages
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let apiMessages = messagesSliceData.messages
|
||||
messages = apiMessages
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
}
|
||||
for message in messages {
|
||||
@@ -926,13 +969,17 @@ func _internal_searchMessageIdByTimestamp(account: Account, peerId: PeerId, thre
|
||||
|> map { result -> MessageIndex? in
|
||||
let messages: [Api.Message]
|
||||
switch result {
|
||||
case let .messages(apiMessages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let apiMessages = messagesData.messages
|
||||
messages = apiMessages
|
||||
case let .channelMessages(_, _, _, _, apiMessages, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let apiMessages = channelMessagesData.messages
|
||||
messages = apiMessages
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let apiMessages = messagesSliceData.messages
|
||||
messages = apiMessages
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
}
|
||||
for message in messages {
|
||||
@@ -950,13 +997,17 @@ func _internal_searchMessageIdByTimestamp(account: Account, peerId: PeerId, thre
|
||||
|> map { result -> MessageIndex? in
|
||||
let messages: [Api.Message]
|
||||
switch result {
|
||||
case let .messages(apiMessages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let apiMessages = messagesData.messages
|
||||
messages = apiMessages
|
||||
case let .channelMessages(_, _, _, _, apiMessages, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let apiMessages = channelMessagesData.messages
|
||||
messages = apiMessages
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let apiMessages = messagesSliceData.messages
|
||||
messages = apiMessages
|
||||
case .messagesNotModified:
|
||||
case let .messagesNotModified(messagesNotModifiedData):
|
||||
let _ = messagesNotModifiedData.count
|
||||
messages = []
|
||||
}
|
||||
for message in messages {
|
||||
@@ -1031,14 +1082,16 @@ func _internal_updatedRemotePeer(accountPeerId: PeerId, postbox: Postbox, networ
|
||||
return postbox.transaction { transaction -> Signal<Peer, UpdatedRemotePeerError> in
|
||||
let chats: [Api.Chat]
|
||||
switch result {
|
||||
case let .chats(c):
|
||||
case let .chats(chatsData):
|
||||
let c = chatsData.chats
|
||||
chats = c
|
||||
case let .chatsSlice(_, c):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let c = chatsSliceData.chats
|
||||
chats = c
|
||||
}
|
||||
|
||||
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
|
||||
|
||||
if let firstId = chats.first?.peerId, let updatedPeer = parsedPeers.get(firstId), updatedPeer.id == peer.id {
|
||||
return postbox.transaction { transaction -> Peer in
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
@@ -1062,9 +1115,11 @@ func _internal_updatedRemotePeer(accountPeerId: PeerId, postbox: Postbox, networ
|
||||
return postbox.transaction { transaction -> Signal<Peer, UpdatedRemotePeerError> in
|
||||
let chats: [Api.Chat]
|
||||
switch result {
|
||||
case let .chats(c):
|
||||
case let .chats(chatsData):
|
||||
let c = chatsData.chats
|
||||
chats = c
|
||||
case let .chatsSlice(_, c):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let c = chatsSliceData.chats
|
||||
chats = c
|
||||
}
|
||||
|
||||
@@ -1102,7 +1157,8 @@ func _internal_refreshGlobalPostSearchState(account: Account) -> Signal<Never, N
|
||||
}
|
||||
transaction.updatePreferencesEntry(key: PreferencesKeys.globalPostSearchState(), { _ in
|
||||
switch result {
|
||||
case let .searchPostsFlood(_, totalDaily, remains, waitTill, starsAmount):
|
||||
case let .searchPostsFlood(searchPostsFloodData):
|
||||
let (_, totalDaily, remains, waitTill, starsAmount) = (searchPostsFloodData.flags, searchPostsFloodData.totalDaily, searchPostsFloodData.remains, searchPostsFloodData.waitTill, searchPostsFloodData.starsAmount)
|
||||
return PreferencesEntry(TelegramGlobalPostSearchState(
|
||||
totalFreeSearches: totalDaily,
|
||||
remainingFreeSearches: remains,
|
||||
|
||||
@@ -130,25 +130,29 @@ func _internal_peerSendAsAvailablePeers(accountPeerId: PeerId, network: Network,
|
||||
return .single([])
|
||||
}
|
||||
switch result {
|
||||
case let .sendAsPeers(sendAsPeers, chats, _):
|
||||
case let .sendAsPeers(sendAsPeersData):
|
||||
let (sendAsPeers, chats) = (sendAsPeersData.peers, sendAsPeersData.chats)
|
||||
return postbox.transaction { transaction -> [SendAsPeer] in
|
||||
var subscribers: [PeerId: Int32] = [:]
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
|
||||
|
||||
var premiumRequiredPeerIds = Set<PeerId>()
|
||||
for sendAsPeer in sendAsPeers {
|
||||
if case let .sendAsPeer(flags, peer) = sendAsPeer, (flags & (1 << 0)) != 0 {
|
||||
if case let .sendAsPeer(sendAsPeerData) = sendAsPeer, (sendAsPeerData.flags & (1 << 0)) != 0 {
|
||||
let peer = sendAsPeerData.peer
|
||||
premiumRequiredPeerIds.insert(peer.peerId)
|
||||
}
|
||||
}
|
||||
for chat in chats {
|
||||
if let groupOrChannel = parsedPeers.get(chat.peerId) {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
}
|
||||
case let .chat(_, _, _, _, participantsCount, _, _, _, _, _):
|
||||
case let .chat(chatData):
|
||||
let participantsCount = chatData.participantsCount
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
default:
|
||||
break
|
||||
@@ -286,25 +290,29 @@ func _internal_liveStorySendAsAvailablePeers(account: Account, peerId: PeerId) -
|
||||
return .single([])
|
||||
}
|
||||
switch result {
|
||||
case let .sendAsPeers(sendAsPeers, chats, _):
|
||||
case let .sendAsPeers(sendAsPeersData):
|
||||
let (sendAsPeers, chats) = (sendAsPeersData.peers, sendAsPeersData.chats)
|
||||
return account.postbox.transaction { transaction -> [SendAsPeer] in
|
||||
var subscribers: [PeerId: Int32] = [:]
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
|
||||
|
||||
var premiumRequiredPeerIds = Set<PeerId>()
|
||||
for sendAsPeer in sendAsPeers {
|
||||
if case let .sendAsPeer(flags, peer) = sendAsPeer, (flags & (1 << 0)) != 0 {
|
||||
if case let .sendAsPeer(sendAsPeerData) = sendAsPeer, (sendAsPeerData.flags & (1 << 0)) != 0 {
|
||||
let peer = sendAsPeerData.peer
|
||||
premiumRequiredPeerIds.insert(peer.peerId)
|
||||
}
|
||||
}
|
||||
for chat in chats {
|
||||
if let groupOrChannel = parsedPeers.get(chat.peerId) {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
}
|
||||
case let .chat(_, _, _, _, participantsCount, _, _, _, _, _):
|
||||
case let .chat(chatData):
|
||||
let participantsCount = chatData.participantsCount
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
default:
|
||||
break
|
||||
|
||||
@@ -86,13 +86,14 @@ public final class SparseMessageList {
|
||||
}
|
||||
private let loadHoleDisposable = MetaDisposable()
|
||||
private var loadingHole: LoadingHole?
|
||||
private var isLoadingInitial: Bool = false
|
||||
|
||||
private var loadingPlaceholders: [MessageId: Disposable] = [:]
|
||||
private var loadedPlaceholders: [MessageId: Message] = [:]
|
||||
|
||||
let statePromise = Promise<SparseMessageList.State>()
|
||||
|
||||
init(queue: Queue, account: Account, peerId: PeerId, threadId: Int64?, messageTag: MessageTags) {
|
||||
init(queue: Queue, account: Account, peerId: PeerId, threadId: Int64?, messageTag: MessageTags, initialMessageIndex: MessageIndex?) {
|
||||
self.queue = queue
|
||||
self.account = account
|
||||
self.peerId = peerId
|
||||
@@ -102,6 +103,11 @@ public final class SparseMessageList {
|
||||
self.resetTopSection()
|
||||
|
||||
if self.threadId == nil {
|
||||
if initialMessageIndex != nil {
|
||||
self.isLoadingInitial = true
|
||||
self.updateState()
|
||||
}
|
||||
|
||||
self.sparseItemsDisposable = (self.account.postbox.transaction { transaction -> Api.InputPeer? in
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
}
|
||||
@@ -112,19 +118,21 @@ public final class SparseMessageList {
|
||||
guard let messageFilter = messageFilterForTagMask(messageTag) else {
|
||||
return .single(SparseItems(items: []))
|
||||
}
|
||||
//TODO:api
|
||||
|
||||
return account.network.request(Api.functions.messages.getSearchResultsPositions(flags: 0, peer: inputPeer, savedPeerId: nil, filter: messageFilter, offsetId: 0, limit: 1000))
|
||||
|> map { result -> SparseItems in
|
||||
switch result {
|
||||
case let .searchResultsPositions(totalCount, positions):
|
||||
case let .searchResultsPositions(searchResultsPositionsData):
|
||||
let (totalCount, apiPositions) = (searchResultsPositionsData.count, searchResultsPositionsData.positions)
|
||||
struct Position: Equatable {
|
||||
var id: Int32
|
||||
var date: Int32
|
||||
var offset: Int
|
||||
}
|
||||
var positions: [Position] = positions.map { position -> Position in
|
||||
var positions: [Position] = apiPositions.map { position -> Position in
|
||||
switch position {
|
||||
case let .searchResultPosition(id, date, offset):
|
||||
case let .searchResultPosition(searchResultPositionData):
|
||||
let (id, date, offset) = (searchResultPositionData.msgId, searchResultPositionData.date, searchResultPositionData.offset)
|
||||
return Position(id: id, date: date, offset: Int(offset))
|
||||
}
|
||||
}
|
||||
@@ -134,7 +142,11 @@ public final class SparseMessageList {
|
||||
|
||||
var result = SparseItems(items: [])
|
||||
for i in 0 ..< positions.count {
|
||||
if i != 0 {
|
||||
if i == 0 {
|
||||
if initialMessageIndex != nil && positions[i].offset != 0 {
|
||||
result.items.append(.range(count: positions[i].offset))
|
||||
}
|
||||
} else {
|
||||
let deltaCount = positions[i].offset - 1 - positions[i - 1].offset
|
||||
if deltaCount > 0 {
|
||||
result.items.append(.range(count: deltaCount))
|
||||
@@ -160,9 +172,34 @@ public final class SparseMessageList {
|
||||
guard let strongSelf = self else {
|
||||
return
|
||||
}
|
||||
strongSelf.isLoadingInitial = false
|
||||
strongSelf.sparseItems = sparseItems
|
||||
if strongSelf.topSection != nil {
|
||||
strongSelf.updateState()
|
||||
if let initialMessageIndex {
|
||||
var loadHoleAnchor: MessageId?
|
||||
loop: for item in sparseItems.items {
|
||||
switch item {
|
||||
case let .anchor(id, timestamp, _):
|
||||
let anchorIndex = MessageIndex(id: id, timestamp: timestamp)
|
||||
if anchorIndex <= initialMessageIndex {
|
||||
loadHoleAnchor = id
|
||||
break loop
|
||||
}
|
||||
case .range:
|
||||
break
|
||||
}
|
||||
}
|
||||
if let loadHoleAnchor {
|
||||
strongSelf.loadHole(anchor: loadHoleAnchor, direction: .around, completion: {
|
||||
})
|
||||
} else {
|
||||
if strongSelf.topSection != nil {
|
||||
strongSelf.updateState()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if strongSelf.topSection != nil {
|
||||
strongSelf.updateState()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -591,10 +628,22 @@ public final class SparseMessageList {
|
||||
if self.topSection != topSection {
|
||||
self.topSection = topSection
|
||||
}
|
||||
self.updateState()
|
||||
if self.loadingHole == nil && !self.isLoadingInitial {
|
||||
self.updateState()
|
||||
}
|
||||
}
|
||||
|
||||
private func updateState() {
|
||||
if self.isLoadingInitial {
|
||||
self.statePromise.set(.single(SparseMessageList.State(
|
||||
items: [],
|
||||
totalCount: 0,
|
||||
isLoading: true
|
||||
)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var items: [SparseMessageList.State.Item] = []
|
||||
var minMessageId: MessageId?
|
||||
if let topSection = self.topSection {
|
||||
@@ -692,11 +741,11 @@ public final class SparseMessageList {
|
||||
}
|
||||
}
|
||||
|
||||
init(account: Account, peerId: PeerId, threadId: Int64?, messageTag: MessageTags) {
|
||||
init(account: Account, peerId: PeerId, threadId: Int64?, messageTag: MessageTags, initialMessageIndex: MessageIndex?) {
|
||||
self.queue = Queue()
|
||||
let queue = self.queue
|
||||
self.impl = QueueLocalObject(queue: queue, generate: {
|
||||
return Impl(queue: queue, account: account, peerId: peerId, threadId: threadId, messageTag: messageTag)
|
||||
return Impl(queue: queue, account: account, peerId: peerId, threadId: threadId, messageTag: messageTag, initialMessageIndex: initialMessageIndex)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -836,7 +885,8 @@ public final class SparseMessageCalendar {
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .searchResultsCalendar(_, _, minDate, minMsgId, _, periods, messages, chats, users):
|
||||
case let .searchResultsCalendar(searchResultsCalendarData):
|
||||
let (minDate, minMsgId, periods, messages, chats, users) = (searchResultsCalendarData.minDate, searchResultsCalendarData.minMsgId, searchResultsCalendarData.periods, searchResultsCalendarData.messages, searchResultsCalendarData.chats, searchResultsCalendarData.users)
|
||||
var parsedMessages: [StoreMessage] = []
|
||||
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
@@ -854,7 +904,8 @@ public final class SparseMessageCalendar {
|
||||
var messagesByDay: [Int32: SparseMessageCalendar.Entry] = [:]
|
||||
for period in periods {
|
||||
switch period {
|
||||
case let .searchResultsCalendarPeriod(date, minMsgId, _, count):
|
||||
case let .searchResultsCalendarPeriod(searchResultsCalendarPeriodData):
|
||||
let (date, minMsgId, count) = (searchResultsCalendarPeriodData.date, searchResultsCalendarPeriodData.minMsgId, searchResultsCalendarPeriodData.count)
|
||||
if let message = transaction.getMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: minMsgId)) {
|
||||
messagesByDay[date] = SparseMessageCalendar.Entry(message: message, count: Int(count))
|
||||
}
|
||||
|
||||
@@ -980,7 +980,7 @@ private func apiInputPrivacyRules(privacy: EngineStoryPrivacy, transaction: Tran
|
||||
privacyRules = [.inputPrivacyValueAllowCloseFriends]
|
||||
case .nobody:
|
||||
if privacy.additionallyIncludePeers.isEmpty {
|
||||
privacyRules = [.inputPrivacyValueAllowUsers(users: [.inputUserSelf])]
|
||||
privacyRules = [.inputPrivacyValueAllowUsers(.init(users: [.inputUserSelf]))]
|
||||
} else {
|
||||
privacyRules = []
|
||||
}
|
||||
@@ -1000,15 +1000,15 @@ private func apiInputPrivacyRules(privacy: EngineStoryPrivacy, transaction: Tran
|
||||
}
|
||||
if !privacyUsers.isEmpty {
|
||||
if case .contacts = privacy.base {
|
||||
privacyRules.append(.inputPrivacyValueDisallowUsers(users: privacyUsers))
|
||||
privacyRules.append(.inputPrivacyValueDisallowUsers(.init(users: privacyUsers)))
|
||||
} else if case .everyone = privacy.base {
|
||||
privacyRules.append(.inputPrivacyValueDisallowUsers(users: privacyUsers))
|
||||
privacyRules.append(.inputPrivacyValueDisallowUsers(.init(users: privacyUsers)))
|
||||
} else {
|
||||
privacyRules.append(.inputPrivacyValueAllowUsers(users: privacyUsers))
|
||||
privacyRules.append(.inputPrivacyValueAllowUsers(.init(users: privacyUsers)))
|
||||
}
|
||||
}
|
||||
if !privacyChats.isEmpty {
|
||||
privacyRules.append(.inputPrivacyValueAllowChatParticipants(chats: privacyChats))
|
||||
privacyRules.append(.inputPrivacyValueAllowChatParticipants(.init(chats: privacyChats)))
|
||||
}
|
||||
return privacyRules
|
||||
}
|
||||
@@ -1155,7 +1155,8 @@ func _internal_beginStoryLivestream(account: Account, peerId: EnginePeer.Id, rtm
|
||||
account.stateManager.addUpdates(updates)
|
||||
|
||||
for update in updates.allUpdates {
|
||||
if case let .updateStory(_, apiStory) = update, case .storyItem = apiStory {
|
||||
if case let .updateStory(updateStoryData) = update, case .storyItem = updateStoryData.story {
|
||||
let apiStory = updateStoryData.story
|
||||
return account.postbox.transaction { transaction in
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: apiStory, peerId: peerId, transaction: transaction), case let .item(item) = storedItem, let media = item.media {
|
||||
let mappedItem = EngineStoryItem(
|
||||
@@ -1389,9 +1390,11 @@ func _internal_uploadStoryImpl(
|
||||
var id: Int32?
|
||||
if let updates = updates {
|
||||
for update in updates.allUpdates {
|
||||
if case let .updateStory(_, story) = update {
|
||||
if case let .updateStory(updateStoryData) = update {
|
||||
let story = updateStoryData.story
|
||||
switch story {
|
||||
case let .storyItem(_, idValue, _, fromId, _, _, _, _, media, _, _, _, _, _):
|
||||
case let .storyItem(storyItemData):
|
||||
let (idValue, fromId, media) = (storyItemData.id, storyItemData.fromId, storyItemData.media)
|
||||
if let parsedStory = Stories.StoredItem(apiStoryItem: story, peerId: toPeerId, transaction: transaction) {
|
||||
var items = transaction.getStoryItems(peerId: toPeerId)
|
||||
var updatedItems: [Stories.Item] = []
|
||||
@@ -1521,7 +1524,8 @@ func _internal_uploadBotPreviewImpl(
|
||||
return .single(.completed(nil))
|
||||
}
|
||||
switch resultPreviewMedia {
|
||||
case let .botPreviewMedia(date, resultMedia):
|
||||
case let .botPreviewMedia(botPreviewMediaData):
|
||||
let (date, resultMedia) = (botPreviewMediaData.date, botPreviewMediaData.media)
|
||||
return postbox.transaction { transaction -> StoryUploadResult in
|
||||
var currentState: Stories.LocalState
|
||||
if let value = transaction.getLocalStoryState()?.get(Stories.LocalState.self) {
|
||||
@@ -1591,10 +1595,10 @@ func _internal_deleteBotPreviews(account: Account, peerId: PeerId, language: Str
|
||||
var inputMedia: [Api.InputMedia] = []
|
||||
for item in media {
|
||||
if let image = item as? TelegramMediaImage, let resource = image.representations.last?.resource as? CloudPhotoSizeMediaResource {
|
||||
inputMedia.append(.inputMediaPhoto(flags: 0, id: .inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(flags: 0, id: Api.InputPhoto.inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(.inputMediaPhoto(.init(flags: 0, id: .inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(.init(flags: 0, id: Api.InputPhoto.inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
} else if let file = item as? TelegramMediaFile, let resource = file.resource as? CloudDocumentMediaResource {
|
||||
inputMedia.append(.inputMediaDocument(flags: 0, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil))
|
||||
inputMedia.append(.inputMediaDocument(.init(flags: 0, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil)))
|
||||
}
|
||||
}
|
||||
if language == nil {
|
||||
@@ -1649,10 +1653,10 @@ func _internal_deleteBotPreviewsLanguage(account: Account, peerId: PeerId, langu
|
||||
var inputMedia: [Api.InputMedia] = []
|
||||
for item in media {
|
||||
if let image = item as? TelegramMediaImage, let resource = image.representations.last?.resource as? CloudPhotoSizeMediaResource {
|
||||
inputMedia.append(.inputMediaPhoto(flags: 0, id: .inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(flags: 0, id: Api.InputPhoto.inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(.inputMediaPhoto(.init(flags: 0, id: .inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(.init(flags: 0, id: Api.InputPhoto.inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
} else if let file = item as? TelegramMediaFile, let resource = file.resource as? CloudDocumentMediaResource {
|
||||
inputMedia.append(.inputMediaDocument(flags: 0, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil))
|
||||
inputMedia.append(.inputMediaDocument(.init(flags: 0, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil)))
|
||||
}
|
||||
}
|
||||
transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, current -> CachedPeerData? in
|
||||
@@ -1717,7 +1721,7 @@ func _internal_editStory(account: Account, peerId: PeerId, id: Int32, media: Eng
|
||||
if let result = result, case let .content(uploadedContent) = result, case let .media(media, _) = uploadedContent.content {
|
||||
inputMedia = media
|
||||
} else if case let .existing(media) = media, let file = media as? TelegramMediaFile, let resource = file.resource as? CloudDocumentMediaResource {
|
||||
inputMedia = .inputMediaUploadedDocument(flags: 0, file: .inputFileStoryDocument(id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), thumb: nil, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil)
|
||||
inputMedia = .inputMediaUploadedDocument(.init(flags: 0, file: .inputFileStoryDocument(.init(id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))))), thumb: nil, mimeType: file.mimeType, attributes: inputDocumentAttributesFromFileAttributes(file.attributes), stickers: nil, videoCover: nil, videoTimestamp: nil, ttlSeconds: nil))
|
||||
updatingCoverTime = true
|
||||
} else {
|
||||
inputMedia = nil
|
||||
@@ -1779,9 +1783,11 @@ func _internal_editStory(account: Account, peerId: PeerId, id: Int32, media: Eng
|
||||
|> mapToSignal { updates -> Signal<StoryUploadResult, NoError> in
|
||||
if let updates = updates {
|
||||
for update in updates.allUpdates {
|
||||
if case let .updateStory(_, story) = update {
|
||||
if case let .updateStory(updateStoryData) = update {
|
||||
let story = updateStoryData.story
|
||||
switch story {
|
||||
case let .storyItem(_, _, _, _, _, _, _, _, media, _, _, _, _, _):
|
||||
case let .storyItem(storyItemData):
|
||||
let media = storyItemData.media
|
||||
let parsedMedia = textMediaAndExpirationTimerFromApiMedia(media, account.peerId).media
|
||||
if let parsedMedia = parsedMedia, let originalMedia = originalMedia {
|
||||
applyMediaResourceChanges(from: originalMedia, to: parsedMedia, postbox: account.postbox, force: false, skipPreviews: updatingCoverTime)
|
||||
@@ -1921,7 +1927,8 @@ func _internal_checkStoriesUploadAvailability(account: Account, target: Stories.
|
||||
return account.network.request(Api.functions.stories.canSendStory(peer: inputPeer))
|
||||
|> map { result -> StoriesUploadAvailability in
|
||||
switch result {
|
||||
case let .canSendStoryCount(countRemains):
|
||||
case let .canSendStoryCount(canSendStoryCountData):
|
||||
let countRemains = canSendStoryCountData.countRemains
|
||||
return .available(remainingCount: countRemains)
|
||||
}
|
||||
}
|
||||
@@ -2146,11 +2153,14 @@ func _internal_updatePinnedToTopStories(account: Account, peerId: PeerId, ids: [
|
||||
extension Api.StoryItem {
|
||||
var id: Int32 {
|
||||
switch self {
|
||||
case let .storyItem(_, id, _, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .storyItem(storyItemData):
|
||||
let id = storyItemData.id
|
||||
return id
|
||||
case let .storyItemDeleted(id):
|
||||
case let .storyItemDeleted(storyItemDeletedData):
|
||||
let id = storyItemDeletedData.id
|
||||
return id
|
||||
case let .storyItemSkipped(_, id, _, _):
|
||||
case let .storyItemSkipped(storyItemSkippedData):
|
||||
let id = storyItemSkippedData.id
|
||||
return id
|
||||
}
|
||||
}
|
||||
@@ -2159,7 +2169,8 @@ extension Api.StoryItem {
|
||||
extension Stories.Item.Views {
|
||||
init(apiViews: Api.StoryViews) {
|
||||
switch apiViews {
|
||||
case let .storyViews(flags, viewsCount, forwardsCount, reactions, reactionsCount, recentViewers):
|
||||
case let .storyViews(storyViewsData):
|
||||
let (flags, viewsCount, forwardsCount, reactions, reactionsCount, recentViewers) = (storyViewsData.flags, storyViewsData.viewsCount, storyViewsData.forwardsCount, storyViewsData.reactions, storyViewsData.reactionsCount, storyViewsData.recentViewers)
|
||||
//storyViews#8d595cd6 flags:# has_viewers:flags.1?true views_count:int forwards_count:flags.2?int reactions:flags.3?Vector<ReactionCount> reactions_count:flags.4?int recent_viewers:flags.0?Vector<long> = StoryViews;
|
||||
let hasList = (flags & (1 << 1)) != 0
|
||||
var seenPeerIds: [PeerId] = []
|
||||
@@ -2170,7 +2181,8 @@ extension Stories.Item.Views {
|
||||
if let reactions = reactions {
|
||||
for result in reactions {
|
||||
switch result {
|
||||
case let .reactionCount(_, chosenOrder, reaction, count):
|
||||
case let .reactionCount(reactionCountData):
|
||||
let (chosenOrder, reaction, count) = (reactionCountData.chosenOrder, reactionCountData.reaction, reactionCountData.count)
|
||||
if let reaction = MessageReaction.Reaction(apiReaction: reaction) {
|
||||
mappedReactions.append(MessageReaction(value: reaction, count: count, chosenOrder: chosenOrder.flatMap(Int.init)))
|
||||
}
|
||||
@@ -2192,7 +2204,8 @@ extension Stories.Item.Views {
|
||||
extension Stories.Item.ForwardInfo {
|
||||
init?(apiForwardInfo: Api.StoryFwdHeader) {
|
||||
switch apiForwardInfo {
|
||||
case let .storyFwdHeader(flags, from, fromName, storyId):
|
||||
case let .storyFwdHeader(storyFwdHeaderData):
|
||||
let (flags, from, fromName, storyId) = (storyFwdHeaderData.flags, storyFwdHeaderData.from, storyFwdHeaderData.fromName, storyFwdHeaderData.storyId)
|
||||
let isModified = (flags & (1 << 3)) != 0
|
||||
if let from = from, let storyId = storyId {
|
||||
self = .known(peerId: from.peerId, storyId: storyId, isModified: isModified)
|
||||
@@ -2209,7 +2222,8 @@ extension Stories.Item.ForwardInfo {
|
||||
extension Stories.StoredItem {
|
||||
init?(apiStoryItem: Api.StoryItem, existingItem: Stories.Item? = nil, peerId: PeerId, transaction: Transaction) {
|
||||
switch apiStoryItem {
|
||||
case let .storyItem(flags, id, date, fromId, forwardFrom, expireDate, caption, entities, media, mediaAreas, privacy, views, sentReaction, albums):
|
||||
case let .storyItem(storyItemData):
|
||||
let (flags, id, date, fromId, forwardFrom, expireDate, caption, entities, media, mediaAreas, privacy, views, sentReaction, albums) = (storyItemData.flags, storyItemData.id, storyItemData.date, storyItemData.fromId, storyItemData.fwdFrom, storyItemData.expireDate, storyItemData.caption, storyItemData.entities, storyItemData.media, storyItemData.mediaAreas, storyItemData.privacy, storyItemData.views, storyItemData.sentReaction, storyItemData.albums)
|
||||
var folderIds: [Int64]?
|
||||
if let albums {
|
||||
folderIds = albums.map(Int64.init)
|
||||
@@ -2233,15 +2247,18 @@ extension Stories.StoredItem {
|
||||
base = .everyone
|
||||
case .privacyValueDisallowAll:
|
||||
base = .nobody
|
||||
case let .privacyValueAllowUsers(users):
|
||||
case let .privacyValueAllowUsers(privacyValueAllowUsersData):
|
||||
let users = privacyValueAllowUsersData.users
|
||||
for id in users {
|
||||
additionalPeerIds.append(EnginePeer.Id(namespace: Namespaces.Peer.CloudUser, id: EnginePeer.Id.Id._internalFromInt64Value(id)))
|
||||
}
|
||||
case let .privacyValueDisallowUsers(users):
|
||||
case let .privacyValueDisallowUsers(privacyValueDisallowUsersData):
|
||||
let users = privacyValueDisallowUsersData.users
|
||||
for id in users {
|
||||
additionalPeerIds.append(EnginePeer.Id(namespace: Namespaces.Peer.CloudUser, id: EnginePeer.Id.Id._internalFromInt64Value(id)))
|
||||
}
|
||||
case let .privacyValueAllowChatParticipants(chats):
|
||||
case let .privacyValueAllowChatParticipants(privacyValueAllowChatParticipantsData):
|
||||
let chats = privacyValueAllowChatParticipantsData.chats
|
||||
for id in chats {
|
||||
if let peer = transaction.getPeer(EnginePeer.Id(namespace: Namespaces.Peer.CloudGroup, id: EnginePeer.Id.Id._internalFromInt64Value(id))) {
|
||||
additionalPeerIds.append(peer.id)
|
||||
@@ -2296,7 +2313,8 @@ extension Stories.StoredItem {
|
||||
|
||||
var parsedAlternativeMedia: [Media] = []
|
||||
switch media {
|
||||
case let .messageMediaDocument(_, _, altDocuments, _, _, _):
|
||||
case let .messageMediaDocument(messageMediaDocumentData):
|
||||
let altDocuments = messageMediaDocumentData.altDocuments
|
||||
if let altDocuments {
|
||||
parsedAlternativeMedia = altDocuments.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: []) }
|
||||
}
|
||||
@@ -2333,7 +2351,8 @@ extension Stories.StoredItem {
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
case let .storyItemSkipped(flags, id, date, expireDate):
|
||||
case let .storyItemSkipped(storyItemSkippedData):
|
||||
let (flags, id, date, expireDate) = (storyItemSkippedData.flags, storyItemSkippedData.id, storyItemSkippedData.date, storyItemSkippedData.expireDate)
|
||||
let isCloseFriends = (flags & (1 << 8)) != 0
|
||||
let isLiveItem = (flags & (1 << 9)) != 0
|
||||
self = .placeholder(Stories.Placeholder(id: id, timestamp: date, expirationTimestamp: expireDate, isCloseFriends: isCloseFriends, isLiveItem: isLiveItem))
|
||||
@@ -2363,9 +2382,10 @@ func _internal_getStoryById(accountPeerId: PeerId, postbox: Postbox, network: Ne
|
||||
}
|
||||
return postbox.transaction { transaction -> EngineStoryItem? in
|
||||
switch result {
|
||||
case let .stories(_, _, stories, _, chats, users):
|
||||
case let .stories(storiesData):
|
||||
let (stories, chats, users) = (storiesData.stories, storiesData.chats, storiesData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
|
||||
|
||||
if let storyItem = stories.first.flatMap({ Stories.StoredItem(apiStoryItem: $0, peerId: peerId, transaction: transaction) }) {
|
||||
if let entry = CodableEntry(storyItem) {
|
||||
transaction.setStory(id: storyId, value: entry)
|
||||
@@ -2431,9 +2451,10 @@ func _internal_getStoriesById(accountPeerId: PeerId, postbox: Postbox, network:
|
||||
}
|
||||
return postbox.transaction { transaction -> [Stories.StoredItem] in
|
||||
switch result {
|
||||
case let .stories(_, _, stories, _, chats, users):
|
||||
case let .stories(storiesData):
|
||||
let (stories, chats, users) = (storiesData.stories, storiesData.chats, storiesData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
|
||||
|
||||
return stories.compactMap { apiStoryItem -> Stories.StoredItem? in
|
||||
return Stories.StoredItem(apiStoryItem: apiStoryItem, peerId: peer.id, transaction: transaction)
|
||||
}
|
||||
@@ -2462,9 +2483,10 @@ func _internal_getStoriesById(accountPeerId: PeerId, postbox: Postbox, source: F
|
||||
}
|
||||
return postbox.transaction { transaction -> [Stories.StoredItem]? in
|
||||
switch result {
|
||||
case let .stories(_, _, stories, _, chats, users):
|
||||
case let .stories(storiesData):
|
||||
let (stories, chats, users) = (storiesData.stories, storiesData.chats, storiesData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
|
||||
|
||||
return stories.compactMap { apiStoryItem -> Stories.StoredItem? in
|
||||
return Stories.StoredItem(apiStoryItem: apiStoryItem, peerId: peerId, transaction: transaction)
|
||||
}
|
||||
@@ -2518,7 +2540,8 @@ func _internal_getStoryViews(account: Account, peerId: PeerId, ids: [Int32]) ->
|
||||
return account.postbox.transaction { transaction -> [Int32: Stories.Item.Views] in
|
||||
var parsedViews: [Int32: Stories.Item.Views] = [:]
|
||||
switch result {
|
||||
case let .storyViews(views, users):
|
||||
case let .storyViews(storyViewsData):
|
||||
let (views, users) = (storyViewsData.views, storyViewsData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
for i in 0 ..< views.count {
|
||||
@@ -2587,7 +2610,8 @@ func _internal_exportStoryLink(account: Account, peerId: EnginePeer.Id, id: Int3
|
||||
return nil
|
||||
}
|
||||
switch result {
|
||||
case let .exportedStoryLink(link):
|
||||
case let .exportedStoryLink(exportedStoryLinkData):
|
||||
let link = exportedStoryLinkData.link
|
||||
return link
|
||||
}
|
||||
}
|
||||
@@ -2645,7 +2669,8 @@ func _internal_refreshSeenStories(postbox: Postbox, network: Network) -> Signal<
|
||||
return postbox.transaction { transaction -> Void in
|
||||
for update in updates.allUpdates {
|
||||
switch update {
|
||||
case let .updateReadStories(peerIdValue, maxId):
|
||||
case let .updateReadStories(updateReadStoriesData):
|
||||
let (peerIdValue, maxId) = (updateReadStoriesData.peer, updateReadStoriesData.maxId)
|
||||
let peerId = peerIdValue.peerId
|
||||
var update = false
|
||||
if let value = transaction.getPeerStoryState(peerId: peerId) {
|
||||
@@ -2693,7 +2718,8 @@ extension Stories.ConfigurationState {
|
||||
extension Stories.StealthModeState {
|
||||
init(apiMode: Api.StoriesStealthMode) {
|
||||
switch apiMode {
|
||||
case let .storiesStealthMode(_, activeUntilDate, cooldownUntilDate):
|
||||
case let .storiesStealthMode(storiesStealthModeData):
|
||||
let (activeUntilDate, cooldownUntilDate) = (storiesStealthModeData.activeUntilDate, storiesStealthModeData.cooldownUntilDate)
|
||||
self.init(
|
||||
activeUntilTimestamp: activeUntilDate,
|
||||
cooldownUntilTimestamp: cooldownUntilDate
|
||||
|
||||
@@ -402,7 +402,8 @@ public final class StorySubscriptionsContext {
|
||||
let _ = (self.postbox.transaction { transaction -> Void in
|
||||
var updatedStealthMode: Api.StoriesStealthMode?
|
||||
switch result {
|
||||
case let .allStoriesNotModified(_, state, stealthMode):
|
||||
case let .allStoriesNotModified(allStoriesNotModifiedData):
|
||||
let (state, stealthMode) = (allStoriesNotModifiedData.state, allStoriesNotModifiedData.stealthMode)
|
||||
self.loadedStateMark = .value(state)
|
||||
let (currentStateValue, _) = transaction.getAllStorySubscriptions(key: subscriptionsKey)
|
||||
let currentState = currentStateValue.flatMap { $0.get(Stories.SubscriptionsState.self) }
|
||||
@@ -421,7 +422,8 @@ public final class StorySubscriptionsContext {
|
||||
if isRefresh && !isHidden {
|
||||
updatedStealthMode = stealthMode
|
||||
}
|
||||
case let .allStories(flags, _, state, peerStories, chats, users, stealthMode):
|
||||
case let .allStories(allStoriesData):
|
||||
let (flags, state, peerStories, chats, users, stealthMode) = (allStoriesData.flags, allStoriesData.state, allStoriesData.peerStories, allStoriesData.chats, allStoriesData.users, allStoriesData.stealthMode)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
let hasMore: Bool = (flags & (1 << 0)) != 0
|
||||
@@ -431,11 +433,12 @@ public final class StorySubscriptionsContext {
|
||||
|
||||
for peerStorySet in peerStories {
|
||||
switch peerStorySet {
|
||||
case let .peerStories(_, peerIdValue, maxReadId, stories):
|
||||
case let .peerStories(peerStoriesData):
|
||||
let (_, peerIdValue, maxReadId, stories) = (peerStoriesData.flags, peerStoriesData.peer, peerStoriesData.maxReadId, peerStoriesData.stories)
|
||||
let peerId = peerIdValue.peerId
|
||||
|
||||
|
||||
let previousPeerEntries: [StoryItemsTableEntry] = transaction.getStoryItems(peerId: peerId)
|
||||
|
||||
|
||||
var updatedPeerEntries: [StoryItemsTableEntry] = []
|
||||
for story in stories {
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peerId, transaction: transaction) {
|
||||
@@ -889,10 +892,12 @@ public final class PeerStoryListContext: StoryListContext {
|
||||
|
||||
if let updatedFolders {
|
||||
switch updatedFolders {
|
||||
case let .albums(_, albums):
|
||||
case let .albums(albumsData):
|
||||
let albums = albumsData.albums
|
||||
for album in albums {
|
||||
switch album {
|
||||
case let .storyAlbum(_, albumId, title, iconPhoto, iconVideo):
|
||||
case let .storyAlbum(storyAlbumData):
|
||||
let (albumId, title, iconPhoto, iconVideo) = (storyAlbumData.albumId, storyAlbumData.title, storyAlbumData.iconPhoto, storyAlbumData.iconVideo)
|
||||
let _ = iconPhoto
|
||||
let _ = iconVideo
|
||||
folderItems.append(State.Folder(
|
||||
@@ -915,7 +920,8 @@ public final class PeerStoryListContext: StoryListContext {
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .stories(_, count, stories, pinnedStories, chats, users):
|
||||
case let .stories(storiesData):
|
||||
let (count, stories, pinnedStories, chats, users) = (storiesData.count, storiesData.stories, storiesData.pinnedToTop, storiesData.chats, storiesData.users)
|
||||
totalCount = Int(count)
|
||||
hasMore = stories.count >= limit
|
||||
|
||||
@@ -1410,7 +1416,8 @@ public final class PeerStoryListContext: StoryListContext {
|
||||
}
|
||||
if let result {
|
||||
switch result {
|
||||
case let .storyAlbum(_, albumId, _, _, _):
|
||||
case let .storyAlbum(storyAlbumData):
|
||||
let albumId = storyAlbumData.albumId
|
||||
var state = self.stateValue
|
||||
state.availableFolders.append(StoryListContextState.Folder(id: Int64(albumId), title: title))
|
||||
self.stateValue = state
|
||||
@@ -1914,7 +1921,8 @@ public final class PeerStoryListContext: StoryListContext {
|
||||
}).start(next: { result in
|
||||
if let result {
|
||||
switch result {
|
||||
case let .storyAlbum(_, albumId, _, _, _):
|
||||
case let .storyAlbum(storyAlbumData):
|
||||
let albumId = storyAlbumData.albumId
|
||||
let _ = (account.postbox.transaction { transaction -> Void in
|
||||
let key = ValueBoxKey(length: 8 + 1)
|
||||
key.setInt64(0, value: peerId.toInt64())
|
||||
@@ -2146,7 +2154,8 @@ public final class SearchStoryListContext: StoryListContext {
|
||||
var nextOffsetValue: String?
|
||||
|
||||
switch result {
|
||||
case let .foundStories(_, count, stories, nextOffset, chats, users):
|
||||
case let .foundStories(foundStoriesData):
|
||||
let (count, stories, nextOffset, chats, users) = (foundStoriesData.count, foundStoriesData.stories, foundStoriesData.nextOffset, foundStoriesData.chats, foundStoriesData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
|
||||
totalCount = Int(count)
|
||||
@@ -2154,7 +2163,8 @@ public final class SearchStoryListContext: StoryListContext {
|
||||
|
||||
for story in stories {
|
||||
switch story {
|
||||
case let .foundStory(peer, story):
|
||||
case let .foundStory(foundStoryData):
|
||||
let (peer, story) = (foundStoryData.peer, foundStoryData.story)
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peer.peerId, transaction: transaction) {
|
||||
if case let .item(item) = storedItem, let media = item.media {
|
||||
let mappedItem = EngineStoryItem(
|
||||
@@ -2593,15 +2603,17 @@ public final class PeerExpiringStoryListContext {
|
||||
var updatedPeerEntries: [StoryItemsTableEntry] = []
|
||||
updatedPeerEntries.removeAll()
|
||||
|
||||
if let result = result, case let .peerStories(stories, chats, users) = result {
|
||||
if let result = result, case let .peerStories(peerStoriesData) = result {
|
||||
let (stories, chats, users) = (peerStoriesData.stories, peerStoriesData.chats, peerStoriesData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
|
||||
switch stories {
|
||||
case let .peerStories(_, peerIdValue, maxReadId, stories):
|
||||
case let .peerStories(peerStoriesData):
|
||||
let (_, peerIdValue, maxReadId, stories) = (peerStoriesData.flags, peerStoriesData.peer, peerStoriesData.maxReadId, peerStoriesData.stories)
|
||||
let peerId = peerIdValue.peerId
|
||||
|
||||
|
||||
let previousPeerEntries: [StoryItemsTableEntry] = transaction.getStoryItems(peerId: peerId)
|
||||
|
||||
|
||||
for story in stories {
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peerId, transaction: transaction) {
|
||||
if case .placeholder = storedItem, let previousEntry = previousPeerEntries.first(where: { $0.id == storedItem.id }) {
|
||||
@@ -2613,15 +2625,15 @@ public final class PeerExpiringStoryListContext {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
transaction.setPeerStoryState(peerId: peerId, state: Stories.PeerState(
|
||||
maxReadId: maxReadId ?? 0
|
||||
).postboxRepresentation)
|
||||
}
|
||||
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
}
|
||||
|
||||
|
||||
transaction.setStoryItems(peerId: peerId, items: updatedPeerEntries)
|
||||
}
|
||||
|> ignoreValues
|
||||
@@ -2774,15 +2786,17 @@ public func _internal_pollPeerStories(postbox: Postbox, network: Network, accoun
|
||||
var updatedPeerEntries: [StoryItemsTableEntry] = []
|
||||
updatedPeerEntries.removeAll()
|
||||
|
||||
if let result = result, case let .peerStories(stories, chats, users) = result {
|
||||
if let result = result, case let .peerStories(peerStoriesData) = result {
|
||||
let (stories, chats, users) = (peerStoriesData.stories, peerStoriesData.chats, peerStoriesData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
|
||||
switch stories {
|
||||
case let .peerStories(_, peerIdValue, maxReadId, stories):
|
||||
case let .peerStories(peerStoriesData):
|
||||
let (_, peerIdValue, maxReadId, stories) = (peerStoriesData.flags, peerStoriesData.peer, peerStoriesData.maxReadId, peerStoriesData.stories)
|
||||
let peerId = peerIdValue.peerId
|
||||
|
||||
|
||||
let previousPeerEntries: [StoryItemsTableEntry] = transaction.getStoryItems(peerId: peerId)
|
||||
|
||||
|
||||
for story in stories {
|
||||
if let storedItem = Stories.StoredItem(apiStoryItem: story, peerId: peerId, transaction: transaction) {
|
||||
if case .placeholder = storedItem, let previousEntry = previousPeerEntries.first(where: { $0.id == storedItem.id }) {
|
||||
@@ -2794,17 +2808,17 @@ public func _internal_pollPeerStories(postbox: Postbox, network: Network, accoun
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
transaction.setPeerStoryState(peerId: peerId, state: Stories.PeerState(
|
||||
maxReadId: maxReadId ?? 0
|
||||
).postboxRepresentation)
|
||||
}
|
||||
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
}
|
||||
|
||||
|
||||
transaction.setStoryItems(peerId: peerId, items: updatedPeerEntries)
|
||||
|
||||
|
||||
var isContactOrMember = false
|
||||
if transaction.isPeerContact(peerId: peerId) {
|
||||
isContactOrMember = true
|
||||
@@ -3373,10 +3387,10 @@ public final class BotPreviewStoryListContext: StoryListContext {
|
||||
var inputMedia: [Api.InputMedia] = []
|
||||
for item in media {
|
||||
if let image = item as? TelegramMediaImage, let resource = image.representations.last?.resource as? CloudPhotoSizeMediaResource {
|
||||
inputMedia.append(.inputMediaPhoto(flags: 0, id: .inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(flags: 0, id: Api.InputPhoto.inputPhoto(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), ttlSeconds: nil))
|
||||
inputMedia.append(.inputMediaPhoto(.init(flags: 0, id: .inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
inputMedia.append(Api.InputMedia.inputMediaPhoto(.init(flags: 0, id: Api.InputPhoto.inputPhoto(.init(id: resource.photoId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), ttlSeconds: nil)))
|
||||
} else if let file = item as? TelegramMediaFile, let resource = file.resource as? CloudDocumentMediaResource {
|
||||
inputMedia.append(.inputMediaDocument(flags: 0, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data())), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil))
|
||||
inputMedia.append(.inputMediaDocument(.init(flags: 0, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference ?? Data()))), videoCover: nil, videoTimestamp: nil, ttlSeconds: nil, query: nil)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,8 @@ func _internal_summarizeMessage(account: Account, messageId: EngineMessage.Id, t
|
||||
|> mapToSignal { result -> Signal<Void, SummarizeError> in
|
||||
return account.postbox.transaction { transaction in
|
||||
switch result {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
transaction.updateMessage(messageId, update: { currentMessage in
|
||||
let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init)
|
||||
var attributes = currentMessage.attributes
|
||||
|
||||
+95
-12
@@ -1,3 +1,4 @@
|
||||
import SGSimpleSettings
|
||||
import Foundation
|
||||
import SwiftSignalKit
|
||||
import Postbox
|
||||
@@ -96,15 +97,22 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func requestMessageActionUrlAuth(subject: MessageActionUrlSubject) -> Signal<MessageActionUrlAuthResult, NoError> {
|
||||
_internal_requestMessageActionUrlAuth(account: self.account, subject: subject)
|
||||
return _internal_requestMessageActionUrlAuth(account: self.account, subject: subject)
|
||||
}
|
||||
|
||||
public func acceptMessageActionUrlAuth(subject: MessageActionUrlSubject, allowWriteAccess: Bool) -> Signal<MessageActionUrlAuthResult, NoError> {
|
||||
return _internal_acceptMessageActionUrlAuth(account: self.account, subject: subject, allowWriteAccess: allowWriteAccess)
|
||||
public func acceptMessageActionUrlAuth(subject: MessageActionUrlSubject, allowWriteAccess: Bool, sharePhoneNumber: Bool) -> Signal<MessageActionUrlAuthResult, MessageActionUrlAuthError> {
|
||||
return _internal_acceptMessageActionUrlAuth(account: self.account, subject: subject, allowWriteAccess: allowWriteAccess, sharePhoneNumber: sharePhoneNumber)
|
||||
}
|
||||
|
||||
public func searchMessages(location: SearchMessagesLocation, query: String, state: SearchMessagesState?, centerId: MessageId? = nil, limit: Int32 = 100) -> Signal<(SearchMessagesResult, SearchMessagesState), NoError> {
|
||||
return _internal_searchMessages(account: self.account, location: location, query: query, state: state, centerId: centerId, limit: limit)
|
||||
// TODO(swiftgram): Try to fallback on error when searching. RX is hard...
|
||||
|> mapToSignal { result -> Signal<(SearchMessagesResult, SearchMessagesState), NoError> in
|
||||
if (result.0.totalCount > 0) {
|
||||
return .single(result)
|
||||
}
|
||||
return _internal_searchMessages(account: self.account, location: location, query: query, state: state, centerId: centerId, limit: limit, forceLocal: true)
|
||||
}
|
||||
}
|
||||
|
||||
public func getSearchMessageCount(location: SearchMessagesLocation, query: String) -> Signal<Int?, NoError> {
|
||||
@@ -399,8 +407,8 @@ public extension TelegramEngine {
|
||||
return _internal_updateStarsReactionPrivacy(account: self.account, messageId: id, privacy: privacy)
|
||||
}
|
||||
|
||||
public func requestChatContextResults(botId: PeerId, peerId: PeerId, query: String, location: Signal<(Double, Double)?, NoError> = .single(nil), offset: String, incompleteResults: Bool = false, staleCachedResults: Bool = false) -> Signal<RequestChatContextResultsResult?, RequestChatContextResultsError> {
|
||||
return _internal_requestChatContextResults(account: self.account, botId: botId, peerId: peerId, query: query, location: location, offset: offset, incompleteResults: incompleteResults, staleCachedResults: staleCachedResults)
|
||||
public func requestChatContextResults(IQTP: Bool = false, botId: PeerId, peerId: PeerId, query: String, location: Signal<(Double, Double)?, NoError> = .single(nil), offset: String, incompleteResults: Bool = false, staleCachedResults: Bool = false) -> Signal<RequestChatContextResultsResult?, RequestChatContextResultsError> {
|
||||
return _internal_requestChatContextResults(IQTP: IQTP, account: self.account, botId: botId, peerId: peerId, query: query, location: location, offset: offset, incompleteResults: incompleteResults, staleCachedResults: staleCachedResults)
|
||||
}
|
||||
|
||||
public func removeRecentlyUsedHashtag(string: String) -> Signal<Void, NoError> {
|
||||
@@ -495,8 +503,8 @@ public extension TelegramEngine {
|
||||
}
|
||||
}
|
||||
|
||||
public func sparseMessageList(peerId: EnginePeer.Id, threadId: Int64?, tag: EngineMessage.Tags) -> SparseMessageList {
|
||||
return SparseMessageList(account: self.account, peerId: peerId, threadId: threadId, messageTag: tag)
|
||||
public func sparseMessageList(peerId: EnginePeer.Id, threadId: Int64?, tag: EngineMessage.Tags, initialMessageIndex: MessageIndex? = nil) -> SparseMessageList {
|
||||
return SparseMessageList(account: self.account, peerId: peerId, threadId: threadId, messageTag: tag, initialMessageIndex: initialMessageIndex)
|
||||
}
|
||||
|
||||
public func sparseMessageCalendar(peerId: EnginePeer.Id, threadId: Int64?, tag: EngineMessage.Tags, displayMedia: Bool) -> SparseMessageCalendar {
|
||||
@@ -544,11 +552,14 @@ public extension TelegramEngine {
|
||||
signals.append(self.account.network.request(Api.functions.messages.search(flags: flags, peer: inputPeer, q: "", fromId: nil, savedPeerId: inputSavedPeer, savedReaction: nil, topMsgId: topMsgId, filter: filter, minDate: 0, maxDate: 0, offsetId: 0, addOffset: 0, limit: 1, maxId: 0, minId: 0, hash: 0))
|
||||
|> map { result -> (count: Int32?, topId: Int32?) in
|
||||
switch result {
|
||||
case let .messagesSlice(_, count, _, _, _, messages, _, _, _):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (count, messages) = (messagesSliceData.count, messagesSliceData.messages)
|
||||
return (count, messages.first?.id(namespace: Namespaces.Message.Cloud)?.id)
|
||||
case let .channelMessages(_, _, count, _, messages, _, _, _):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (count, messages) = (channelMessagesData.count, channelMessagesData.messages)
|
||||
return (count, messages.first?.id(namespace: Namespaces.Message.Cloud)?.id)
|
||||
case let .messages(messages, _, _, _):
|
||||
case let .messages(messagesData):
|
||||
let messages = messagesData.messages
|
||||
return (Int32(messages.count), messages.first?.id(namespace: Namespaces.Message.Cloud)?.id)
|
||||
case .messagesNotModified:
|
||||
return (nil, nil)
|
||||
@@ -589,11 +600,16 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func translate(text: String, toLang: String, entities: [MessageTextEntity] = []) -> Signal<(String, [MessageTextEntity])?, TranslationError> {
|
||||
return _internal_translate(network: self.account.network, text: text, toLang: toLang, entities: entities)
|
||||
return sgWrappedTranslateSingle(text: text, toLang: toLang, default: _internal_translate(network: self.account.network, text: text, toLang: toLang, entities: entities))
|
||||
}
|
||||
|
||||
public func translate(texts: [(String, [MessageTextEntity])], toLang: String) -> Signal<[(String, [MessageTextEntity])], TranslationError> {
|
||||
return _internal_translateTexts(network: self.account.network, texts: texts, toLang: toLang)
|
||||
return sgWrappedTranslateMultiple(texts: texts,toLang: toLang, default: _internal_translateTexts(network: self.account.network, texts: texts, toLang: toLang))
|
||||
}
|
||||
|
||||
// MARK: Swiftgram
|
||||
public func translateMessagesViaText(messagesDict: [EngineMessage.Id: String], fromLang: String?, toLang: String, generateEntitiesFunction: @escaping (String) -> [MessageTextEntity], enableLocalIfPossible: Bool) -> Signal<Never, TranslationError> {
|
||||
return _internal_translateMessagesViaText(account: self.account, messagesDict: messagesDict, fromLang: fromLang, toLang: toLang, enableLocalIfPossible: enableLocalIfPossible, generateEntitiesFunction: generateEntitiesFunction)
|
||||
}
|
||||
|
||||
public func translateMessages(messageIds: [EngineMessage.Id], fromLang: String?, toLang: String, enableLocalIfPossible: Bool) -> Signal<Never, TranslationError> {
|
||||
@@ -1471,6 +1487,10 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func markStoryAsSeen(peerId: EnginePeer.Id, id: Int32, asPinned: Bool) -> Signal<Never, NoError> {
|
||||
// MARK: Swiftgram
|
||||
if SGSimpleSettings.shared.isStealthModeEnabled {
|
||||
return .never()
|
||||
}
|
||||
return _internal_markStoryAsSeen(account: self.account, peerId: peerId, id: id, asPinned: asPinned)
|
||||
}
|
||||
|
||||
@@ -1707,3 +1727,66 @@ func _internal_monoforumPerformSuggestedPostAction(account: Account, id: EngineM
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// MARK: Swiftgram
|
||||
private func sgWrappedTranslateSingle(
|
||||
text: String,
|
||||
toLang: String,
|
||||
`default`: Signal<(String, [MessageTextEntity])?, TranslationError>
|
||||
) -> Signal<(String, [MessageTextEntity])?, TranslationError> {
|
||||
if SGSimpleSettings.shared.translationBackend == SGSimpleSettings.TranslationBackend.gtranslate.rawValue {
|
||||
return gtranslate(text, toLang)
|
||||
|> map { ($0, []) }
|
||||
|> mapError { _ in .generic }
|
||||
}
|
||||
|
||||
return `default`
|
||||
|> `catch` { originalError in
|
||||
gtranslate(text, toLang)
|
||||
|> map { ($0, []) }
|
||||
|> mapError { _ in originalError }
|
||||
}
|
||||
}
|
||||
|
||||
private func sgWrappedTranslateMultiple(
|
||||
texts: [(String, [MessageTextEntity])],
|
||||
toLang: String,
|
||||
`default`: Signal<[(String, [MessageTextEntity])], TranslationError>
|
||||
) -> Signal<[(String, [MessageTextEntity])], TranslationError> {
|
||||
if SGSimpleSettings.shared.translationBackend == SGSimpleSettings.TranslationBackend.gtranslate.rawValue {
|
||||
let translatedSignals: [Signal<(String, [MessageTextEntity]), TranslationError>] = texts.map { (text, _) in
|
||||
gtranslate(text, toLang)
|
||||
|> map { ($0, []) }
|
||||
|> mapError { _ in .generic }
|
||||
}
|
||||
return combineLatest(translatedSignals)
|
||||
}
|
||||
|
||||
return `default`
|
||||
|> `catch` { originalError in
|
||||
let translatedSignals: [Signal<(String, [MessageTextEntity]), TranslationError>] = texts.map { (text, _) in
|
||||
gtranslate(text, toLang)
|
||||
|> map { ($0, []) }
|
||||
|> mapError { _ in originalError }
|
||||
}
|
||||
return combineLatest(translatedSignals)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,11 +85,13 @@ func _internal_keepCachedTimeZoneListUpdated(account: Account) -> Signal<Never,
|
||||
|
||||
return account.postbox.transaction { transaction in
|
||||
switch result {
|
||||
case let .timezonesList(timezones, hash):
|
||||
case let .timezonesList(timezonesListData):
|
||||
let (timezones, hash) = (timezonesListData.timezones, timezonesListData.hash)
|
||||
var items: [TimeZoneList.Item] = []
|
||||
for item in timezones {
|
||||
switch item {
|
||||
case let .timezone(id, name, utcOffset):
|
||||
case let .timezone(timezoneData):
|
||||
let (id, name, utcOffset) = (timezoneData.id, timezoneData.name, timezoneData.utcOffset)
|
||||
items.append(TimeZoneList.Item(id: id, title: name, utcOffset: utcOffset))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,8 @@ func _internal_transcribeAudio(postbox: Postbox, network: Network, messageId: Me
|
||||
switch result {
|
||||
case let .success(transcribedAudio):
|
||||
switch transcribedAudio {
|
||||
case let .transcribedAudio(flags, transcriptionId, text, trialRemainingCount, trialUntilDate):
|
||||
case let .transcribedAudio(transcribedAudioData):
|
||||
let (flags, transcriptionId, text, trialRemainingCount, trialUntilDate) = (transcribedAudioData.flags, transcribedAudioData.transcriptionId, transcribedAudioData.text, transcribedAudioData.trialRemainsNum, transcribedAudioData.trialRemainsUntilDate)
|
||||
let isPending = (flags & (1 << 0)) != 0
|
||||
updatedAttribute = AudioTranscriptionMessageAttribute(id: transcriptionId, text: text, isPending: isPending, didRate: false, error: nil)
|
||||
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
#if DEBUG
|
||||
import SGSimpleSettings
|
||||
#endif
|
||||
import SGTranslationLangFix
|
||||
import SwiftSoup
|
||||
|
||||
import Foundation
|
||||
import Postbox
|
||||
import SwiftSignalKit
|
||||
@@ -18,7 +24,7 @@ func _internal_translate(network: Network, text: String, toLang: String, entitie
|
||||
var flags: Int32 = 0
|
||||
flags |= (1 << 1)
|
||||
|
||||
return network.request(Api.functions.messages.translateText(flags: flags, peer: nil, id: nil, text: [.textWithEntities(text: text, entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary()))], toLang: toLang))
|
||||
return network.request(Api.functions.messages.translateText(flags: flags, peer: nil, id: nil, text: [.textWithEntities(.init(text: text, entities: apiEntitiesFromMessageTextEntities(entities, associatedPeers: SimpleDictionary())))], toLang: sgTranslationLangFix(toLang)))
|
||||
|> mapError { error -> TranslationError in
|
||||
if error.errorDescription.hasPrefix("FLOOD_WAIT") {
|
||||
return .limitExceeded
|
||||
@@ -38,8 +44,10 @@ func _internal_translate(network: Network, text: String, toLang: String, entitie
|
||||
}
|
||||
|> mapToSignal { result -> Signal<(String, [MessageTextEntity])?, TranslationError> in
|
||||
switch result {
|
||||
case let .translateResult(results):
|
||||
if case let .textWithEntities(text, entities) = results.first {
|
||||
case let .translateResult(translateResultData):
|
||||
let results = translateResultData.result
|
||||
if case let .textWithEntities(textWithEntitiesData) = results.first {
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
return .single((text, messageTextEntitiesFromApiEntities(entities)))
|
||||
} else {
|
||||
return .single(nil)
|
||||
@@ -54,7 +62,7 @@ func _internal_translateTexts(network: Network, texts: [(String, [MessageTextEnt
|
||||
|
||||
var apiTexts: [Api.TextWithEntities] = []
|
||||
for text in texts {
|
||||
apiTexts.append(.textWithEntities(text: text.0, entities: apiEntitiesFromMessageTextEntities(text.1, associatedPeers: SimpleDictionary())))
|
||||
apiTexts.append(.textWithEntities(.init(text: text.0, entities: apiEntitiesFromMessageTextEntities(text.1, associatedPeers: SimpleDictionary()))))
|
||||
}
|
||||
|
||||
return network.request(Api.functions.messages.translateText(flags: flags, peer: nil, id: nil, text: apiTexts, toLang: toLang))
|
||||
@@ -76,9 +84,11 @@ func _internal_translateTexts(network: Network, texts: [(String, [MessageTextEnt
|
||||
|> mapToSignal { result -> Signal<[(String, [MessageTextEntity])], TranslationError> in
|
||||
var texts: [(String, [MessageTextEntity])] = []
|
||||
switch result {
|
||||
case let .translateResult(results):
|
||||
case let .translateResult(translateResultData):
|
||||
let results = translateResultData.result
|
||||
for result in results {
|
||||
if case let .textWithEntities(text, entities) = result {
|
||||
if case let .textWithEntities(textWithEntitiesData) = result {
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
texts.append((text, messageTextEntitiesFromApiEntities(entities)))
|
||||
}
|
||||
}
|
||||
@@ -176,18 +186,18 @@ private func _internal_translateMessagesByPeerId(account: Account, peerId: Engin
|
||||
var result: [Api.TextWithEntities] = []
|
||||
for messageId in messageIds {
|
||||
if let text = resultTexts[AnyHashable(messageId)] {
|
||||
result.append(.textWithEntities(text: text, entities: []))
|
||||
result.append(.textWithEntities(.init(text: text, entities: [])))
|
||||
} else if let text = messageTexts[messageId] {
|
||||
result.append(.textWithEntities(text: text, entities: []))
|
||||
result.append(.textWithEntities(.init(text: text, entities: [])))
|
||||
} else {
|
||||
result.append(.textWithEntities(text: "", entities: []))
|
||||
result.append(.textWithEntities(.init(text: "", entities: [])))
|
||||
}
|
||||
}
|
||||
return .single(.translateResult(result: result))
|
||||
return .single(.translateResult(.init(result: result)))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
msgs = account.network.request(Api.functions.messages.translateText(flags: flags, peer: inputPeer, id: id, text: nil, toLang: toLang))
|
||||
msgs = account.network.request(Api.functions.messages.translateText(flags: flags, peer: inputPeer, id: id, text: nil, toLang: sgTranslationLangFix(toLang)))
|
||||
|> map(Optional.init)
|
||||
|> mapError { error -> TranslationError in
|
||||
if error.errorDescription.hasPrefix("FLOOD_WAIT") {
|
||||
@@ -210,11 +220,13 @@ private func _internal_translateMessagesByPeerId(account: Account, peerId: Engin
|
||||
return combineLatest(msgs, combineLatest(pollSignals), combineLatest(audioTranscriptionsSignals))
|
||||
|> mapToSignal { (result, pollResults, audioTranscriptionsResults) -> Signal<Void, TranslationError> in
|
||||
return account.postbox.transaction { transaction in
|
||||
if case let .translateResult(results) = result {
|
||||
if case let .translateResult(translateResultData) = result {
|
||||
let results = translateResultData.result
|
||||
var index = 0
|
||||
for result in results {
|
||||
let messageId = messageIds[index]
|
||||
if case let .textWithEntities(text, entities) = result {
|
||||
if case let .textWithEntities(textWithEntitiesData) = result {
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
let updatedAttribute: TranslationMessageAttribute = TranslationMessageAttribute(text: text, entities: messageTextEntitiesFromApiEntities(entities), toLang: toLang)
|
||||
transaction.updateMessage(messageId, update: { currentMessage in
|
||||
let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init)
|
||||
@@ -284,6 +296,42 @@ private func _internal_translateMessagesByPeerId(account: Account, peerId: Engin
|
||||
}
|
||||
}
|
||||
|
||||
func _internal_translateMessagesViaText(account: Account, messagesDict: [EngineMessage.Id: String], fromLang: String?, toLang: String, enableLocalIfPossible: Bool, generateEntitiesFunction: @escaping (String) -> [MessageTextEntity]) -> Signal<Never, TranslationError> {
|
||||
var listOfSignals: [Signal<Void, TranslationError>] = []
|
||||
for (messageId, text) in messagesDict {
|
||||
listOfSignals.append(
|
||||
// _internal_translate(network: account.network, text: text, toLang: toLang)
|
||||
// |> mapToSignal { result -> Signal<Void, TranslationError> in
|
||||
// guard let translatedText = result else {
|
||||
// return .complete()
|
||||
// }
|
||||
gtranslate(text, toLang)
|
||||
|> mapError { _ -> TranslationError in
|
||||
return .generic
|
||||
}
|
||||
|> mapToSignal { translatedText -> Signal<Void, TranslationError> in
|
||||
// guard case let .result(translatedText) = result else {
|
||||
// return .complete()
|
||||
// }
|
||||
return account.postbox.transaction { transaction in
|
||||
transaction.updateMessage(messageId, update: { currentMessage in
|
||||
let updatedAttribute: TranslationMessageAttribute = TranslationMessageAttribute(text: translatedText, entities: generateEntitiesFunction(translatedText), toLang: toLang)
|
||||
let storeForwardInfo = currentMessage.forwardInfo.flatMap(StoreMessageForwardInfo.init)
|
||||
var attributes = currentMessage.attributes.filter { !($0 is TranslationMessageAttribute) }
|
||||
|
||||
attributes.append(updatedAttribute)
|
||||
|
||||
return .update(StoreMessage(id: currentMessage.id, customStableId: nil, globallyUniqueId: currentMessage.globallyUniqueId, groupingKey: currentMessage.groupingKey, threadId: currentMessage.threadId, timestamp: currentMessage.timestamp, flags: StoreMessageFlags(currentMessage.flags), tags: currentMessage.tags, globalTags: currentMessage.globalTags, localTags: currentMessage.localTags, forwardInfo: storeForwardInfo, authorId: currentMessage.author?.id, text: currentMessage.text, attributes: attributes, media: currentMessage.media))
|
||||
})
|
||||
}
|
||||
|> castError(TranslationError.self)
|
||||
// |> castError(TranslateFetchError.self)
|
||||
}
|
||||
)
|
||||
}
|
||||
return combineLatest(listOfSignals) |> ignoreValues
|
||||
}
|
||||
|
||||
func _internal_togglePeerMessagesTranslationHidden(account: Account, peerId: EnginePeer.Id, hidden: Bool) -> Signal<Never, NoError> {
|
||||
return account.postbox.transaction { transaction -> Api.InputPeer? in
|
||||
transaction.updatePeerCachedData(peerIds: Set([peerId]), update: { _, cachedData -> CachedPeerData? in
|
||||
@@ -334,3 +382,249 @@ func _internal_togglePeerMessagesTranslationHidden(account: Account, peerId: Eng
|
||||
|> ignoreValues
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(swiftgram): Refactor
|
||||
public struct TranslateRule: Codable {
|
||||
public let name: String
|
||||
public let pattern: String
|
||||
public let data_check: String
|
||||
public let match_group: Int
|
||||
}
|
||||
|
||||
public func getTranslateUrl(_ message: String,_ toLang: String) -> String {
|
||||
let sanitizedMessage = message // message.replaceCharactersFromSet(characterSet:CharacterSet.newlines, replacementString: "<br>")
|
||||
|
||||
var queryCharSet = NSCharacterSet.urlQueryAllowed
|
||||
queryCharSet.remove(charactersIn: "+&")
|
||||
return "https://translate.google.com/m?hl=en&tl=\(toLang)&sl=auto&q=\(sanitizedMessage.addingPercentEncoding(withAllowedCharacters: queryCharSet) ?? "")"
|
||||
}
|
||||
|
||||
func prepareResultString(_ str: String) -> String {
|
||||
return str
|
||||
// return str.htmlDecoded.replacingOccurrences(of: "<br>", with: "\n").replacingOccurrences(of: "< br>", with: "\n").replacingOccurrences(of: "<br >", with: "\n")
|
||||
}
|
||||
|
||||
var regexCache: [String: NSRegularExpression] = [:]
|
||||
|
||||
public func parseTranslateResponse(_ data: String) -> String {
|
||||
do {
|
||||
let document = try SwiftSoup.parse(data)
|
||||
|
||||
if let resultContainer = try document.select("div.result-container").first() {
|
||||
// new_mobile
|
||||
return prepareResultString(try resultContainer.text())
|
||||
} else if let tZero = try document.select("div.t0").first() {
|
||||
// old_mobile
|
||||
return prepareResultString(try tZero.text())
|
||||
}
|
||||
} catch Exception.Error(let type, let message) {
|
||||
#if DEBUG
|
||||
SGtrace("translate", what: "Translation parser failure, An error of type \(type) occurred: \(message)")
|
||||
#endif
|
||||
// print("Translation parser failure, An error of type \(type) occurred: \(message)")
|
||||
} catch {
|
||||
#if DEBUG
|
||||
SGtrace("translate", what: "Translation parser failure, An error occurred: \(error)")
|
||||
#endif
|
||||
// print("Translation parser failure, An error occurred: \(error)")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
public func getGTranslateLang(_ userLang: String) -> String {
|
||||
var lang = userLang
|
||||
let rawSuffix = "-raw"
|
||||
if lang.hasSuffix(rawSuffix) {
|
||||
lang = String(lang.dropLast(rawSuffix.count))
|
||||
}
|
||||
lang = lang.lowercased()
|
||||
|
||||
// Fallback To Google lang
|
||||
switch (lang) {
|
||||
case "zh-hans", "zh":
|
||||
return "zh-CN"
|
||||
case "zh-hant":
|
||||
return "zh-TW"
|
||||
case "he":
|
||||
return "iw"
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
// Fix for pt-br and other regional langs
|
||||
// https://cloud.go
|
||||
// ogle.com/tran
|
||||
// slate/do
|
||||
// cs/lang
|
||||
// uages
|
||||
lang = lang.components(separatedBy: "-")[0].components(separatedBy: "_")[0]
|
||||
|
||||
return lang
|
||||
}
|
||||
|
||||
|
||||
public enum TranslateFetchError {
|
||||
case network
|
||||
}
|
||||
|
||||
|
||||
let TranslateSessionConfiguration = URLSessionConfiguration.ephemeral
|
||||
|
||||
// Create a URLSession with the ephemeral configuration
|
||||
let TranslateSession = URLSession(configuration: TranslateSessionConfiguration)
|
||||
|
||||
public func requestTranslateUrl(url: URL) -> Signal<String, TranslateFetchError> {
|
||||
return Signal { subscriber in
|
||||
let completed = Atomic<Bool>(value: false)
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = "GET"
|
||||
// Set headers
|
||||
request.setValue("Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)", forHTTPHeaderField: "User-Agent")
|
||||
let downloadTask = TranslateSession.dataTask(with: request, completionHandler: { data, response, error in
|
||||
let _ = completed.swap(true)
|
||||
if let response = response as? HTTPURLResponse {
|
||||
if response.statusCode == 200 {
|
||||
if let data = data {
|
||||
if let result = String(data: data, encoding: .utf8) {
|
||||
subscriber.putNext(result)
|
||||
subscriber.putCompletion()
|
||||
} else {
|
||||
subscriber.putError(.network)
|
||||
}
|
||||
} else {
|
||||
// print("Empty data")
|
||||
subscriber.putError(.network)
|
||||
}
|
||||
} else {
|
||||
// print("Non 200 status")
|
||||
subscriber.putError(.network)
|
||||
}
|
||||
} else {
|
||||
// print("No response (??)")
|
||||
subscriber.putError(.network)
|
||||
}
|
||||
})
|
||||
downloadTask.resume()
|
||||
|
||||
return ActionDisposable {
|
||||
if !completed.with({ $0 }) {
|
||||
downloadTask.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func gtranslate(_ text: String, _ toLang: String) -> Signal<String, TranslateFetchError> {
|
||||
// 1) Preserve *all* line breaks, including empty ones
|
||||
let lines = text.components(separatedBy: "\n")
|
||||
|
||||
// 2) Map each line to either a passthrough signal or a translate signal
|
||||
let translationSignals: [Signal<String, TranslateFetchError>] = lines.map { rawLine in
|
||||
// Grab the "core" text and its leading whitespace
|
||||
let leadingWhitespace = rawLine.prefix { $0.isWhitespace }
|
||||
let core = rawLine.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
// If there’s nothing to translate, just emit the line back
|
||||
if core.isEmpty {
|
||||
return .single(rawLine)
|
||||
}
|
||||
|
||||
// Otherwise translate the core, then re-attach the indentation
|
||||
return gtranslateSentence(core, toLang)
|
||||
|> map { translatedCore in
|
||||
return String(leadingWhitespace) + translatedCore
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Combine them and re-join with newlines
|
||||
return combineLatest(translationSignals)
|
||||
|> map { results in
|
||||
let joined = results.joined(separator: "\n")
|
||||
return joined.isEmpty ? text : joined
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public func gtranslateSentence(_ text: String, _ toLang: String) -> Signal<String, TranslateFetchError> {
|
||||
return Signal { subscriber in
|
||||
let urlString = getTranslateUrl(text, getGTranslateLang(toLang))
|
||||
let url = URL(string: urlString)!
|
||||
let translateSignal = requestTranslateUrl(url: url)
|
||||
var translateDisposable: Disposable? = nil
|
||||
|
||||
translateDisposable = translateSignal.start(next: {
|
||||
translatedHtml in
|
||||
#if DEBUG
|
||||
print("urlString: \(urlString)")
|
||||
let startTime = CFAbsoluteTimeGetCurrent()
|
||||
print("translatedHtml: \(translatedHtml)")
|
||||
print("decodedHtml: \(translatedHtml.htmlDecoded)")
|
||||
#endif
|
||||
let result = parseTranslateResponse(translatedHtml)
|
||||
#if DEBUG
|
||||
print("translatedResult: \(result)")
|
||||
SGtrace("translate", what: "Translation parsed in \(CFAbsoluteTimeGetCurrent() - startTime)")
|
||||
#endif
|
||||
if result.isEmpty {
|
||||
// print("EMPTY RESULT")
|
||||
subscriber.putError(.network) // Fake
|
||||
} else {
|
||||
subscriber.putNext(result)
|
||||
subscriber.putCompletion()
|
||||
}
|
||||
|
||||
}, error: { _ in
|
||||
subscriber.putError(.network)
|
||||
})
|
||||
|
||||
return ActionDisposable {
|
||||
translateDisposable?.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func gtranslateSplitTextBySentences(_ text: String, maxChunkLength: Int = 1500) -> [String] {
|
||||
if text.count <= maxChunkLength {
|
||||
return [text]
|
||||
}
|
||||
var chunks: [String] = []
|
||||
var currentChunk = ""
|
||||
|
||||
text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .bySentences) { (substring, _, _, _) in
|
||||
guard let sentence = substring else { return }
|
||||
|
||||
if currentChunk.count + sentence.count + 1 < maxChunkLength {
|
||||
currentChunk += sentence + " "
|
||||
} else {
|
||||
if !currentChunk.isEmpty {
|
||||
chunks.append(currentChunk.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
}
|
||||
currentChunk = sentence + " "
|
||||
}
|
||||
}
|
||||
|
||||
if !currentChunk.isEmpty {
|
||||
chunks.append(currentChunk.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
}
|
||||
|
||||
return chunks
|
||||
}
|
||||
|
||||
|
||||
extension String {
|
||||
var htmlDecoded: String {
|
||||
let attributedOptions: [NSAttributedString.DocumentReadingOptionKey : Any] = [
|
||||
NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html,
|
||||
NSAttributedString.DocumentReadingOptionKey.characterEncoding : String.Encoding.utf8.rawValue
|
||||
]
|
||||
|
||||
let decoded = try? NSAttributedString(data: Data(utf8), options: attributedOptions, documentAttributes: nil).string
|
||||
return decoded ?? self
|
||||
}
|
||||
|
||||
func replaceCharactersFromSet(characterSet: CharacterSet, replacementString: String = "") -> String {
|
||||
return components(separatedBy: characterSet).joined(separator: replacementString)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,8 @@ func _internal_requestUpdatePinnedMessage(account: Account, peerId: PeerId, upda
|
||||
account.stateManager.addUpdates(updates)
|
||||
return account.postbox.transaction { transaction in
|
||||
switch updates {
|
||||
case let .updates(updates, _, _, _, _):
|
||||
case let .updates(updatesData):
|
||||
let updates = updatesData.updates
|
||||
if updates.isEmpty {
|
||||
if peerId.namespace == Namespaces.Peer.CloudChannel {
|
||||
let messageId: MessageId
|
||||
@@ -173,7 +174,8 @@ func _internal_requestUnpinAllMessages(account: Account, peerId: PeerId, threadI
|
||||
}
|
||||
|> mapToSignal { result -> Signal<Bool, InternalError> in
|
||||
switch result {
|
||||
case let .affectedHistory(_, _, count):
|
||||
case let .affectedHistory(affectedHistoryData):
|
||||
let count = affectedHistoryData.offset
|
||||
if count != 0 {
|
||||
return .fail(.restart)
|
||||
}
|
||||
|
||||
@@ -35,14 +35,14 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
default:
|
||||
break
|
||||
}
|
||||
return .single(.inputStorePaymentPremiumSubscription(flags: flags))
|
||||
return .single(.inputStorePaymentPremiumSubscription(.init(flags: flags)))
|
||||
case let .gift(peerId, currency, amount):
|
||||
return postbox.loadedPeerWithId(peerId)
|
||||
|> mapToSignal { peer -> Signal<Api.InputStorePaymentPurpose, NoError> in
|
||||
guard let inputUser = apiInputUser(peer) else {
|
||||
return .complete()
|
||||
}
|
||||
return .single(.inputStorePaymentGiftPremium(userId: inputUser, currency: currency, amount: amount))
|
||||
return .single(.inputStorePaymentGiftPremium(.init(userId: inputUser, currency: currency, amount: amount)))
|
||||
}
|
||||
case let .giftCode(peerIds, boostPeerId, currency, amount, text, entities):
|
||||
return postbox.transaction { transaction -> Api.InputStorePaymentPurpose in
|
||||
@@ -64,10 +64,10 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
var message: Api.TextWithEntities?
|
||||
if let text, !text.isEmpty {
|
||||
flags |= (1 << 1)
|
||||
message = .textWithEntities(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? [])
|
||||
message = .textWithEntities(.init(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? []))
|
||||
}
|
||||
|
||||
return .inputStorePaymentPremiumGiftCode(flags: flags, users: apiInputUsers, boostPeer: apiBoostPeer, currency: currency, amount: amount, message: message)
|
||||
return .inputStorePaymentPremiumGiftCode(.init(flags: flags, users: apiInputUsers, boostPeer: apiBoostPeer, currency: currency, amount: amount, message: message))
|
||||
}
|
||||
case let .giveaway(boostPeerId, additionalPeerIds, countries, onlyNewSubscribers, showWinners, prizeDescription, randomId, untilDate, currency, amount):
|
||||
return postbox.transaction { transaction -> Signal<Api.InputStorePaymentPurpose, NoError> in
|
||||
@@ -96,7 +96,7 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
if let _ = prizeDescription {
|
||||
flags |= (1 << 4)
|
||||
}
|
||||
return .single(.inputStorePaymentPremiumGiveaway(flags: flags, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount))
|
||||
return .single(.inputStorePaymentPremiumGiveaway(.init(flags: flags, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount)))
|
||||
}
|
||||
|> switchToLatest
|
||||
case let .stars(count, currency, amount, peerId):
|
||||
@@ -115,7 +115,7 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
if let _ = spendPurposePeer {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return .inputStorePaymentStarsTopup(flags: flags, stars: count, currency: currency, amount: amount, spendPurposePeer: spendPurposePeer)
|
||||
return .inputStorePaymentStarsTopup(.init(flags: flags, stars: count, currency: currency, amount: amount, spendPurposePeer: spendPurposePeer))
|
||||
}
|
||||
case let .starsGift(peerId, count, currency, amount):
|
||||
return postbox.loadedPeerWithId(peerId)
|
||||
@@ -123,7 +123,7 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
guard let inputUser = apiInputUser(peer) else {
|
||||
return .complete()
|
||||
}
|
||||
return .single(.inputStorePaymentStarsGift(userId: inputUser, stars: count, currency: currency, amount: amount))
|
||||
return .single(.inputStorePaymentStarsGift(.init(userId: inputUser, stars: count, currency: currency, amount: amount)))
|
||||
}
|
||||
case let .starsGiveaway(stars, boostPeerId, additionalPeerIds, countries, onlyNewSubscribers, showWinners, prizeDescription, randomId, untilDate, currency, amount, users):
|
||||
return postbox.transaction { transaction -> Signal<Api.InputStorePaymentPurpose, NoError> in
|
||||
@@ -152,7 +152,7 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
if let _ = prizeDescription {
|
||||
flags |= (1 << 4)
|
||||
}
|
||||
return .single(.inputStorePaymentStarsGiveaway(flags: flags, stars: stars, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount, users: users))
|
||||
return .single(.inputStorePaymentStarsGiveaway(.init(flags: flags, stars: stars, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount, users: users)))
|
||||
}
|
||||
|> switchToLatest
|
||||
case let .authCode(restore, phoneNumber, phoneCodeHash, currency, amount):
|
||||
@@ -160,7 +160,7 @@ private func apiInputStorePaymentPurpose(postbox: Postbox, purpose: AppStoreTran
|
||||
if restore {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return .single(.inputStorePaymentAuthCode(flags: flags, phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash, currency: currency, amount: amount))
|
||||
return .single(.inputStorePaymentAuthCode(.init(flags: flags, phoneNumber: phoneNumber, phoneCodeHash: phoneCodeHash, currency: currency, amount: amount)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,8 @@ public struct BankCardInfo {
|
||||
extension BankCardUrl {
|
||||
init(apiBankCardOpenUrl: Api.BankCardOpenUrl) {
|
||||
switch apiBankCardOpenUrl {
|
||||
case let .bankCardOpenUrl(url, name):
|
||||
case let .bankCardOpenUrl(bankCardOpenUrlData):
|
||||
let (url, name) = (bankCardOpenUrlData.url, bankCardOpenUrlData.name)
|
||||
self.title = name
|
||||
self.url = url
|
||||
}
|
||||
@@ -50,7 +51,8 @@ extension BankCardUrl {
|
||||
extension BankCardInfo {
|
||||
init(apiBankCardData: Api.payments.BankCardData) {
|
||||
switch apiBankCardData {
|
||||
case let .bankCardData(title, urls):
|
||||
case let .bankCardData(bankCardDataData):
|
||||
let (title, urls) = (bankCardDataData.title, bankCardDataData.openUrls)
|
||||
self.title = title
|
||||
self.urls = urls.map { BankCardUrl(apiBankCardOpenUrl: $0) }
|
||||
}
|
||||
|
||||
@@ -171,7 +171,8 @@ public struct BotPaymentMethod: Equatable {
|
||||
extension BotPaymentMethod {
|
||||
init(apiPaymentFormMethod: Api.PaymentFormMethod) {
|
||||
switch apiPaymentFormMethod {
|
||||
case let .paymentFormMethod(url, title):
|
||||
case let .paymentFormMethod(paymentFormMethodData):
|
||||
let (url, title) = (paymentFormMethodData.url, paymentFormMethodData.title)
|
||||
self.init(url: url, title: title)
|
||||
}
|
||||
}
|
||||
@@ -189,7 +190,8 @@ public enum BotPaymentFormRequestError {
|
||||
extension BotPaymentInvoice {
|
||||
init(apiInvoice: Api.Invoice) {
|
||||
switch apiInvoice {
|
||||
case let .invoice(flags, currency, prices, maxTipAmount, suggestedTipAmounts, termsUrl, subscriptionPeriod):
|
||||
case let .invoice(invoiceData):
|
||||
let (flags, currency, prices, maxTipAmount, suggestedTipAmounts, termsUrl, subscriptionPeriod) = (invoiceData.flags, invoiceData.currency, invoiceData.prices, invoiceData.maxTipAmount, invoiceData.suggestedTipAmounts, invoiceData.termsUrl, invoiceData.subscriptionPeriod)
|
||||
var fields = BotPaymentInvoiceFields()
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
fields.insert(.name)
|
||||
@@ -223,7 +225,8 @@ extension BotPaymentInvoice {
|
||||
}
|
||||
self.init(isTest: (flags & (1 << 0)) != 0, requestedFields: fields, currency: currency, prices: prices.map {
|
||||
switch $0 {
|
||||
case let .labeledPrice(label, amount):
|
||||
case let .labeledPrice(labeledPriceData):
|
||||
let (label, amount) = (labeledPriceData.label, labeledPriceData.amount)
|
||||
return BotPaymentPrice(label: label, amount: amount)
|
||||
}
|
||||
}, tip: parsedTip, termsInfo: termsInfo, subscriptionPeriod: subscriptionPeriod)
|
||||
@@ -234,11 +237,13 @@ extension BotPaymentInvoice {
|
||||
extension BotPaymentRequestedInfo {
|
||||
init(apiInfo: Api.PaymentRequestedInfo) {
|
||||
switch apiInfo {
|
||||
case let .paymentRequestedInfo(_, name, phone, email, shippingAddress):
|
||||
case let .paymentRequestedInfo(paymentRequestedInfoData):
|
||||
let (name, phone, email, shippingAddress) = (paymentRequestedInfoData.name, paymentRequestedInfoData.phone, paymentRequestedInfoData.email, paymentRequestedInfoData.shippingAddress)
|
||||
var parsedShippingAddress: BotPaymentShippingAddress?
|
||||
if let shippingAddress = shippingAddress {
|
||||
switch shippingAddress {
|
||||
case let .postAddress(streetLine1, streetLine2, city, state, countryIso2, postCode):
|
||||
case let .postAddress(postAddressData):
|
||||
let (streetLine1, streetLine2, city, state, countryIso2, postCode) = (postAddressData.streetLine1, postAddressData.streetLine2, postAddressData.city, postAddressData.state, postAddressData.countryIso2, postAddressData.postCode)
|
||||
parsedShippingAddress = BotPaymentShippingAddress(streetLine1: streetLine1, streetLine2: streetLine2, city: city, state: state, countryIso2: countryIso2, postCode: postCode)
|
||||
}
|
||||
}
|
||||
@@ -253,9 +258,9 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
guard let inputPeer = transaction.getPeer(messageId.peerId).flatMap(apiInputPeer) else {
|
||||
return nil
|
||||
}
|
||||
return .inputInvoiceMessage(peer: inputPeer, msgId: messageId.id)
|
||||
return .inputInvoiceMessage(.init(peer: inputPeer, msgId: messageId.id))
|
||||
case let .slug(slug):
|
||||
return .inputInvoiceSlug(slug: slug)
|
||||
return .inputInvoiceSlug(.init(slug: slug))
|
||||
case let .premiumGiveaway(boostPeerId, additionalPeerIds, countries, onlyNewSubscribers, showWinners, prizeDescription, randomId, untilDate, currency, amount, option):
|
||||
guard let peer = transaction.getPeer(boostPeerId), let apiBoostPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
@@ -283,7 +288,7 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
flags |= (1 << 4)
|
||||
}
|
||||
|
||||
let inputPurpose: Api.InputStorePaymentPurpose = .inputStorePaymentPremiumGiveaway(flags: flags, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount)
|
||||
let inputPurpose: Api.InputStorePaymentPurpose = .inputStorePaymentPremiumGiveaway(.init(flags: flags, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount))
|
||||
|
||||
flags = 0
|
||||
|
||||
@@ -294,9 +299,9 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
flags |= (1 << 1)
|
||||
}
|
||||
|
||||
let option: Api.PremiumGiftCodeOption = .premiumGiftCodeOption(flags: flags, users: option.users, months: option.months, storeProduct: option.storeProductId, storeQuantity: option.storeQuantity, currency: option.currency, amount: option.amount)
|
||||
let option: Api.PremiumGiftCodeOption = .premiumGiftCodeOption(.init(flags: flags, users: option.users, months: option.months, storeProduct: option.storeProductId, storeQuantity: option.storeQuantity, currency: option.currency, amount: option.amount))
|
||||
|
||||
return .inputInvoicePremiumGiftCode(purpose: inputPurpose, option: option)
|
||||
return .inputInvoicePremiumGiftCode(.init(purpose: inputPurpose, option: option))
|
||||
case let .giftCode(users, currency, amount, option, text, entities):
|
||||
var inputUsers: [Api.InputUser] = []
|
||||
if !users.isEmpty {
|
||||
@@ -311,10 +316,10 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
var message: Api.TextWithEntities?
|
||||
if let text, !text.isEmpty {
|
||||
inputPurposeFlags |= (1 << 1)
|
||||
message = .textWithEntities(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? [])
|
||||
message = .textWithEntities(.init(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? []))
|
||||
}
|
||||
|
||||
let inputPurpose: Api.InputStorePaymentPurpose = .inputStorePaymentPremiumGiftCode(flags: inputPurposeFlags, users: inputUsers, boostPeer: nil, currency: currency, amount: amount, message: message)
|
||||
let inputPurpose: Api.InputStorePaymentPurpose = .inputStorePaymentPremiumGiftCode(.init(flags: inputPurposeFlags, users: inputUsers, boostPeer: nil, currency: currency, amount: amount, message: message))
|
||||
|
||||
var flags: Int32 = 0
|
||||
if let _ = option.storeProductId {
|
||||
@@ -324,9 +329,9 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
flags |= (1 << 1)
|
||||
}
|
||||
|
||||
let option: Api.PremiumGiftCodeOption = .premiumGiftCodeOption(flags: flags, users: option.users, months: option.months, storeProduct: option.storeProductId, storeQuantity: option.storeQuantity, currency: option.currency, amount: option.amount)
|
||||
let option: Api.PremiumGiftCodeOption = .premiumGiftCodeOption(.init(flags: flags, users: option.users, months: option.months, storeProduct: option.storeProductId, storeQuantity: option.storeQuantity, currency: option.currency, amount: option.amount))
|
||||
|
||||
return .inputInvoicePremiumGiftCode(purpose: inputPurpose, option: option)
|
||||
return .inputInvoicePremiumGiftCode(.init(purpose: inputPurpose, option: option))
|
||||
case let .stars(option, peerId):
|
||||
var flags: Int32 = 0
|
||||
var spendPurposePeer: Api.InputPeer?
|
||||
@@ -334,14 +339,14 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
flags |= (1 << 0)
|
||||
spendPurposePeer = inputPeer
|
||||
}
|
||||
return .inputInvoiceStars(purpose: .inputStorePaymentStarsTopup(flags: flags, stars: option.count, currency: option.currency, amount: option.amount, spendPurposePeer: spendPurposePeer))
|
||||
return .inputInvoiceStars(.init(purpose: .inputStorePaymentStarsTopup(.init(flags: flags, stars: option.count, currency: option.currency, amount: option.amount, spendPurposePeer: spendPurposePeer))))
|
||||
case let .starsGift(peerId, count, currency, amount):
|
||||
guard let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) else {
|
||||
return nil
|
||||
}
|
||||
return .inputInvoiceStars(purpose: .inputStorePaymentStarsGift(userId: inputUser, stars: count, currency: currency, amount: amount))
|
||||
return .inputInvoiceStars(.init(purpose: .inputStorePaymentStarsGift(.init(userId: inputUser, stars: count, currency: currency, amount: amount))))
|
||||
case let .starsChatSubscription(hash):
|
||||
return .inputInvoiceChatInviteSubscription(hash: hash)
|
||||
return .inputInvoiceChatInviteSubscription(.init(hash: hash))
|
||||
case let .starsGiveaway(stars, boostPeerId, additionalPeerIds, countries, onlyNewSubscribers, showWinners, prizeDescription, randomId, untilDate, currency, amount, users):
|
||||
guard let peer = transaction.getPeer(boostPeerId), let apiBoostPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
@@ -368,7 +373,7 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
if let _ = prizeDescription {
|
||||
flags |= (1 << 4)
|
||||
}
|
||||
return .inputInvoiceStars(purpose: .inputStorePaymentStarsGiveaway(flags: flags, stars: stars, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount, users: users))
|
||||
return .inputInvoiceStars(.init(purpose: .inputStorePaymentStarsGiveaway(.init(flags: flags, stars: stars, boostPeer: apiBoostPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: currency, amount: amount, users: users))))
|
||||
case let .starGift(hideName, includeUpgrade, peerId, giftId, text, entities):
|
||||
guard let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
@@ -383,20 +388,20 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
var message: Api.TextWithEntities?
|
||||
if let text, !text.isEmpty {
|
||||
flags |= (1 << 1)
|
||||
message = .textWithEntities(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? [])
|
||||
message = .textWithEntities(.init(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? []))
|
||||
}
|
||||
return .inputInvoiceStarGift(flags: flags, peer: inputPeer, giftId: giftId, message: message)
|
||||
return .inputInvoiceStarGift(.init(flags: flags, peer: inputPeer, giftId: giftId, message: message))
|
||||
case let .starGiftUpgrade(keepOriginalInfo, reference):
|
||||
var flags: Int32 = 0
|
||||
if keepOriginalInfo {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftUpgrade(flags: flags, stargift: $0) }
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftUpgrade(.init(flags: flags, stargift: $0)) }
|
||||
case let .starGiftTransfer(reference, toPeerId):
|
||||
guard let peer = transaction.getPeer(toPeerId), let inputPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
}
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftTransfer(stargift: $0, toId: inputPeer) }
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftTransfer(.init(stargift: $0, toId: inputPeer)) }
|
||||
case let .premiumGift(peerId, option, text, entities):
|
||||
guard let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) else {
|
||||
return nil
|
||||
@@ -405,9 +410,9 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
var message: Api.TextWithEntities?
|
||||
if let text, !text.isEmpty {
|
||||
flags |= (1 << 0)
|
||||
message = .textWithEntities(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? [])
|
||||
message = .textWithEntities(.init(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? []))
|
||||
}
|
||||
return .inputInvoicePremiumGiftStars(flags: flags, userId: inputUser, months: option.months, message: message)
|
||||
return .inputInvoicePremiumGiftStars(.init(flags: flags, userId: inputUser, months: option.months, message: message))
|
||||
case let .starGiftResale(slug, toPeerId, ton):
|
||||
guard let peer = transaction.getPeer(toPeerId), let inputPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
@@ -416,14 +421,14 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
if ton {
|
||||
flags |= 1 << 0
|
||||
}
|
||||
return .inputInvoiceStarGiftResale(flags: flags, slug: slug, toId: inputPeer)
|
||||
return .inputInvoiceStarGiftResale(.init(flags: flags, slug: slug, toId: inputPeer))
|
||||
case let .starGiftPrepaidUpgrade(peerId, hash):
|
||||
guard let peer = transaction.getPeer(peerId), let inputPeer = apiInputPeer(peer) else {
|
||||
return nil
|
||||
}
|
||||
return .inputInvoiceStarGiftPrepaidUpgrade(peer: inputPeer, hash: hash)
|
||||
return .inputInvoiceStarGiftPrepaidUpgrade(.init(peer: inputPeer, hash: hash))
|
||||
case let .starGiftDropOriginalDetails(reference):
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftDropOriginalDetails(stargift: $0) }
|
||||
return reference.apiStarGiftReference(transaction: transaction).flatMap { .inputInvoiceStarGiftDropOriginalDetails(.init(stargift: $0)) }
|
||||
|
||||
case let .starGiftAuctionBid(update, hideName, peerId, giftId, bidAmount, text, entities):
|
||||
var flags: Int32 = 0
|
||||
@@ -445,10 +450,10 @@ func _internal_parseInputInvoice(transaction: Transaction, source: BotPaymentInv
|
||||
|
||||
if let text, !text.isEmpty {
|
||||
flags |= (1 << 1)
|
||||
message = .textWithEntities(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? [])
|
||||
message = .textWithEntities(.init(text: text, entities: entities.flatMap { apiEntitiesFromMessageTextEntities($0, associatedPeers: SimpleDictionary()) } ?? []))
|
||||
}
|
||||
}
|
||||
return .inputInvoiceStarGiftAuctionBid(flags: flags, peer: inputPeer, giftId: giftId, bidAmount: bidAmount, message: message)
|
||||
return .inputInvoiceStarGiftAuctionBid(.init(flags: flags, peer: inputPeer, giftId: giftId, bidAmount: bidAmount, message: message))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,7 +480,8 @@ func _internal_fetchBotPaymentInvoice(postbox: Postbox, network: Network, source
|
||||
|> mapToSignal { result -> Signal<TelegramMediaInvoice, BotPaymentFormRequestError> in
|
||||
return postbox.transaction { transaction -> TelegramMediaInvoice in
|
||||
switch result {
|
||||
case let .paymentForm(_, _, _, title, description, photo, invoice, _, _, _, _, _, _, _, _):
|
||||
case let .paymentForm(paymentFormData):
|
||||
let (title, description, photo, invoice) = (paymentFormData.title, paymentFormData.description, paymentFormData.photo, paymentFormData.invoice)
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
|
||||
var parsedFlags = TelegramMediaInvoiceFlags()
|
||||
@@ -487,10 +493,12 @@ func _internal_fetchBotPaymentInvoice(postbox: Postbox, network: Network, source
|
||||
}
|
||||
|
||||
return TelegramMediaInvoice(title: title, description: description, photo: photo.flatMap(TelegramMediaWebFile.init), receiptMessageId: nil, currency: parsedInvoice.currency, totalAmount: 0, startParam: "", extendedMedia: nil, subscriptionPeriod: parsedInvoice.subscriptionPeriod, flags: parsedFlags, version: TelegramMediaInvoice.lastVersion)
|
||||
case let .paymentFormStars(_, _, _, title, description, photo, invoice, _):
|
||||
case let .paymentFormStars(paymentFormStarsData):
|
||||
let (title, description, photo, invoice) = (paymentFormStarsData.title, paymentFormStarsData.description, paymentFormStarsData.photo, paymentFormStarsData.invoice)
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
return TelegramMediaInvoice(title: title, description: description, photo: photo.flatMap(TelegramMediaWebFile.init), receiptMessageId: nil, currency: parsedInvoice.currency, totalAmount: parsedInvoice.prices.reduce(0, { $0 + $1.amount }), startParam: "", extendedMedia: nil, subscriptionPeriod: parsedInvoice.subscriptionPeriod, flags: [], version: TelegramMediaInvoice.lastVersion)
|
||||
case let .paymentFormStarGift(_, invoice):
|
||||
case let .paymentFormStarGift(paymentFormStarGiftData):
|
||||
let invoice = paymentFormStarGiftData.invoice
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
return TelegramMediaInvoice(title: "", description: "", photo: nil, receiptMessageId: nil, currency: parsedInvoice.currency, totalAmount: parsedInvoice.prices.reduce(0, { $0 + $1.amount }), startParam: "", extendedMedia: nil, subscriptionPeriod: parsedInvoice.subscriptionPeriod, flags: [], version: TelegramMediaInvoice.lastVersion)
|
||||
}
|
||||
@@ -513,7 +521,7 @@ func _internal_fetchBotPaymentForm(accountPeerId: PeerId, postbox: Postbox, netw
|
||||
var flags: Int32 = 0
|
||||
var serializedThemeParams: Api.DataJSON?
|
||||
if let themeParams = themeParams, let data = try? JSONSerialization.data(withJSONObject: themeParams, options: []), let dataString = String(data: data, encoding: .utf8) {
|
||||
serializedThemeParams = Api.DataJSON.dataJSON(data: dataString)
|
||||
serializedThemeParams = Api.DataJSON.dataJSON(.init(data: dataString))
|
||||
}
|
||||
if serializedThemeParams != nil {
|
||||
flags |= 1 << 0
|
||||
@@ -538,11 +546,12 @@ func _internal_fetchBotPaymentForm(accountPeerId: PeerId, postbox: Postbox, netw
|
||||
|> mapToSignal { result -> Signal<BotPaymentForm, BotPaymentFormRequestError> in
|
||||
return postbox.transaction { transaction -> BotPaymentForm in
|
||||
switch result {
|
||||
case let .paymentForm(flags, id, botId, title, description, photo, invoice, providerId, url, nativeProvider, nativeParams, additionalMethods, savedInfo, savedCredentials, apiUsers):
|
||||
case let .paymentForm(paymentFormData):
|
||||
let (flags, id, botId, title, description, photo, invoice, providerId, url, nativeProvider, nativeParams, additionalMethods, savedInfo, savedCredentials, apiUsers) = (paymentFormData.flags, paymentFormData.formId, paymentFormData.botId, paymentFormData.title, paymentFormData.description, paymentFormData.photo, paymentFormData.invoice, paymentFormData.providerId, paymentFormData.url, paymentFormData.nativeProvider, paymentFormData.nativeParams, paymentFormData.additionalMethods, paymentFormData.savedInfo, paymentFormData.savedCredentials, paymentFormData.users)
|
||||
let _ = title
|
||||
let _ = description
|
||||
let _ = photo
|
||||
|
||||
|
||||
let parsedPeers = AccumulatedPeers(users: apiUsers)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -550,33 +559,37 @@ func _internal_fetchBotPaymentForm(accountPeerId: PeerId, postbox: Postbox, netw
|
||||
var parsedNativeProvider: BotPaymentNativeProvider?
|
||||
if let nativeProvider = nativeProvider, let nativeParams = nativeParams {
|
||||
switch nativeParams {
|
||||
case let .dataJSON(data):
|
||||
case let .dataJSON(dataJSONData):
|
||||
let data = dataJSONData.data
|
||||
parsedNativeProvider = BotPaymentNativeProvider(name: nativeProvider, params: data)
|
||||
}
|
||||
}
|
||||
let parsedSavedInfo = savedInfo.flatMap(BotPaymentRequestedInfo.init)
|
||||
let parsedSavedCredentials = savedCredentials?.map({ savedCredentials -> BotPaymentSavedCredentials in
|
||||
switch savedCredentials {
|
||||
case let .paymentSavedCredentialsCard(id, title):
|
||||
case let .paymentSavedCredentialsCard(paymentSavedCredentialsCardData):
|
||||
let (id, title) = (paymentSavedCredentialsCardData.id, paymentSavedCredentialsCardData.title)
|
||||
return .card(id: id, title: title)
|
||||
}
|
||||
}) ?? []
|
||||
|
||||
let additionalPaymentMethods = additionalMethods?.map({ BotPaymentMethod(apiPaymentFormMethod: $0) }) ?? []
|
||||
return BotPaymentForm(id: id, canSaveCredentials: (flags & (1 << 2)) != 0, passwordMissing: (flags & (1 << 3)) != 0, invoice: parsedInvoice, paymentBotId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), providerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(providerId)), url: url, nativeProvider: parsedNativeProvider, savedInfo: parsedSavedInfo, savedCredentials: parsedSavedCredentials, additionalPaymentMethods: additionalPaymentMethods)
|
||||
case let .paymentFormStars(flags, id, botId, title, description, photo, invoice, apiUsers):
|
||||
case let .paymentFormStars(paymentFormStarsData):
|
||||
let (flags, id, botId, title, description, photo, invoice, apiUsers) = (paymentFormStarsData.flags, paymentFormStarsData.formId, paymentFormStarsData.botId, paymentFormStarsData.title, paymentFormStarsData.description, paymentFormStarsData.photo, paymentFormStarsData.invoice, paymentFormStarsData.users)
|
||||
let _ = flags
|
||||
let _ = title
|
||||
let _ = description
|
||||
let _ = photo
|
||||
|
||||
|
||||
let parsedPeers = AccumulatedPeers(users: apiUsers)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
return BotPaymentForm(id: id, canSaveCredentials: false, passwordMissing: false, invoice: parsedInvoice, paymentBotId: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)), providerId: nil, url: nil, nativeProvider: nil, savedInfo: nil, savedCredentials: [], additionalPaymentMethods: [])
|
||||
|
||||
case let .paymentFormStarGift(id, invoice):
|
||||
case let .paymentFormStarGift(paymentFormStarGiftData):
|
||||
let (id, invoice) = (paymentFormStarGiftData.formId, paymentFormStarGiftData.invoice)
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
return BotPaymentForm(id: id, canSaveCredentials: false, passwordMissing: false, invoice: parsedInvoice, paymentBotId: nil, providerId: nil, url: nil, nativeProvider: nil, savedInfo: nil, savedCredentials: [], additionalPaymentMethods: [])
|
||||
}
|
||||
@@ -611,10 +624,12 @@ public struct BotPaymentValidatedFormInfo : Equatable {
|
||||
extension BotPaymentShippingOption {
|
||||
init(apiOption: Api.ShippingOption) {
|
||||
switch apiOption {
|
||||
case let .shippingOption(id, title, prices):
|
||||
case let .shippingOption(shippingOptionData):
|
||||
let (id, title, prices) = (shippingOptionData.id, shippingOptionData.title, shippingOptionData.prices)
|
||||
self.init(id: id, title: title, prices: prices.map {
|
||||
switch $0 {
|
||||
case let .labeledPrice(label, amount):
|
||||
case let .labeledPrice(labeledPriceData):
|
||||
let (label, amount) = (labeledPriceData.label, labeledPriceData.amount)
|
||||
return BotPaymentPrice(label: label, amount: amount)
|
||||
}
|
||||
})
|
||||
@@ -649,9 +664,9 @@ func _internal_validateBotPaymentForm(account: Account, saveInfo: Bool, source:
|
||||
var apiShippingAddress: Api.PostAddress?
|
||||
if let address = formInfo.shippingAddress {
|
||||
infoFlags |= (1 << 3)
|
||||
apiShippingAddress = .postAddress(streetLine1: address.streetLine1, streetLine2: address.streetLine2, city: address.city, state: address.state, countryIso2: address.countryIso2, postCode: address.postCode)
|
||||
apiShippingAddress = .postAddress(.init(streetLine1: address.streetLine1, streetLine2: address.streetLine2, city: address.city, state: address.state, countryIso2: address.countryIso2, postCode: address.postCode))
|
||||
}
|
||||
return account.network.request(Api.functions.payments.validateRequestedInfo(flags: flags, invoice: invoice, info: .paymentRequestedInfo(flags: infoFlags, name: formInfo.name, phone: formInfo.phone, email: formInfo.email, shippingAddress: apiShippingAddress)))
|
||||
return account.network.request(Api.functions.payments.validateRequestedInfo(flags: flags, invoice: invoice, info: .paymentRequestedInfo(.init(flags: infoFlags, name: formInfo.name, phone: formInfo.phone, email: formInfo.email, shippingAddress: apiShippingAddress))))
|
||||
|> mapError { error -> ValidateBotPaymentFormError in
|
||||
if error.errorDescription == "SHIPPING_NOT_AVAILABLE" {
|
||||
return .shippingNotAvailable
|
||||
@@ -673,7 +688,8 @@ func _internal_validateBotPaymentForm(account: Account, saveInfo: Bool, source:
|
||||
}
|
||||
|> map { result -> BotPaymentValidatedFormInfo in
|
||||
switch result {
|
||||
case let .validatedRequestedInfo(_, id, shippingOptions):
|
||||
case let .validatedRequestedInfo(validatedRequestedInfoData):
|
||||
let (id, shippingOptions) = (validatedRequestedInfoData.id, validatedRequestedInfoData.shippingOptions)
|
||||
return BotPaymentValidatedFormInfo(id: id, shippingOptions: shippingOptions.flatMap {
|
||||
return $0.map(BotPaymentShippingOption.init)
|
||||
})
|
||||
@@ -721,11 +737,11 @@ func _internal_sendBotPaymentForm(account: Account, formId: Int64, source: BotPa
|
||||
if saveOnServer {
|
||||
credentialsFlags |= (1 << 0)
|
||||
}
|
||||
apiCredentials = .inputPaymentCredentials(flags: credentialsFlags, data: .dataJSON(data: data))
|
||||
apiCredentials = .inputPaymentCredentials(.init(flags: credentialsFlags, data: .dataJSON(.init(data: data))))
|
||||
case let .saved(id, tempPassword):
|
||||
apiCredentials = .inputPaymentCredentialsSaved(id: id, tmpPassword: Buffer(data: tempPassword))
|
||||
apiCredentials = .inputPaymentCredentialsSaved(.init(id: id, tmpPassword: Buffer(data: tempPassword)))
|
||||
case let .applePay(data):
|
||||
apiCredentials = .inputPaymentCredentialsApplePay(paymentData: .dataJSON(data: data))
|
||||
apiCredentials = .inputPaymentCredentialsApplePay(.init(paymentData: .dataJSON(.init(data: data))))
|
||||
}
|
||||
var flags: Int32 = 0
|
||||
if validatedInfoId != nil {
|
||||
@@ -741,7 +757,8 @@ func _internal_sendBotPaymentForm(account: Account, formId: Int64, source: BotPa
|
||||
return account.network.request(Api.functions.payments.sendPaymentForm(flags: flags, formId: formId, invoice: invoice, requestedInfoId: validatedInfoId, shippingOptionId: shippingOptionId, credentials: apiCredentials, tipAmount: tipAmount))
|
||||
|> map { result -> SendBotPaymentResult in
|
||||
switch result {
|
||||
case let .paymentResult(updates):
|
||||
case let .paymentResult(paymentResultData):
|
||||
let updates = paymentResultData.updates
|
||||
account.stateManager.addUpdates(updates)
|
||||
var receiptMessageId: MessageId?
|
||||
|
||||
@@ -800,7 +817,8 @@ func _internal_sendBotPaymentForm(account: Account, formId: Int64, source: BotPa
|
||||
}
|
||||
}
|
||||
return .done(receiptMessageId: receiptMessageId, subscriptionPeerId: nil, uniqueStarGift: nil)
|
||||
case let .paymentVerificationNeeded(url):
|
||||
case let .paymentVerificationNeeded(paymentVerificationNeededData):
|
||||
let url = paymentVerificationNeededData.url
|
||||
return .externalVerificationRequired(url: url)
|
||||
}
|
||||
}
|
||||
@@ -882,7 +900,8 @@ func _internal_requestBotPaymentReceipt(account: Account, messageId: MessageId)
|
||||
|> mapToSignal { result -> Signal<BotPaymentReceipt, RequestBotPaymentReceiptError> in
|
||||
return account.postbox.transaction { transaction -> BotPaymentReceipt in
|
||||
switch result {
|
||||
case let .paymentReceipt(_, date, botId, _, title, description, photo, invoice, info, shipping, tipAmount, currency, totalAmount, credentialsTitle, users):
|
||||
case let .paymentReceipt(paymentReceiptData):
|
||||
let (date, botId, title, description, photo, invoice, info, shipping, tipAmount, currency, totalAmount, credentialsTitle, users) = (paymentReceiptData.date, paymentReceiptData.botId, paymentReceiptData.title, paymentReceiptData.description, paymentReceiptData.photo, paymentReceiptData.invoice, paymentReceiptData.info, paymentReceiptData.shipping, paymentReceiptData.tipAmount, paymentReceiptData.currency, paymentReceiptData.totalAmount, paymentReceiptData.credentialsTitle, paymentReceiptData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -903,16 +922,17 @@ func _internal_requestBotPaymentReceipt(account: Account, messageId: MessageId)
|
||||
flags: [],
|
||||
version: TelegramMediaInvoice.lastVersion
|
||||
)
|
||||
|
||||
|
||||
let botPaymentId = PeerId.init(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId))
|
||||
|
||||
return BotPaymentReceipt(invoice: parsedInvoice, date: date, info: parsedInfo, shippingOption: shippingOption, credentialsTitle: credentialsTitle, invoiceMedia: invoiceMedia, tipAmount: tipAmount, botPaymentId: botPaymentId, transactionId: nil)
|
||||
case let .paymentReceiptStars(_, date, botId, title, description, photo, invoice, currency, totalAmount, transactionId, users):
|
||||
case let .paymentReceiptStars(paymentReceiptStarsData):
|
||||
let (date, botId, title, description, photo, invoice, currency, totalAmount, transactionId, users) = (paymentReceiptStarsData.date, paymentReceiptStarsData.botId, paymentReceiptStarsData.title, paymentReceiptStarsData.description, paymentReceiptStarsData.photo, paymentReceiptStarsData.invoice, paymentReceiptStarsData.currency, paymentReceiptStarsData.totalAmount, paymentReceiptStarsData.transactionId, paymentReceiptStarsData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
let parsedInvoice = BotPaymentInvoice(apiInvoice: invoice)
|
||||
|
||||
|
||||
let invoiceMedia = TelegramMediaInvoice(
|
||||
title: title,
|
||||
description: description,
|
||||
@@ -926,7 +946,7 @@ func _internal_requestBotPaymentReceipt(account: Account, messageId: MessageId)
|
||||
flags: [],
|
||||
version: TelegramMediaInvoice.lastVersion
|
||||
)
|
||||
|
||||
|
||||
let botPaymentId = PeerId.init(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId))
|
||||
return BotPaymentReceipt(invoice: parsedInvoice, date: date, info: nil, shippingOption: nil, credentialsTitle: "", invoiceMedia: invoiceMedia, tipAmount: nil, botPaymentId: botPaymentId, transactionId: transactionId)
|
||||
}
|
||||
|
||||
@@ -114,7 +114,8 @@ func _internal_getPremiumGiveawayInfo(account: Account, peerId: EnginePeer.Id, m
|
||||
|> map { result -> PremiumGiveawayInfo? in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .giveawayInfo(flags, startDate, joinedTooEarlyDate, adminDisallowedChatId, disallowedCountry):
|
||||
case let .giveawayInfo(giveawayInfoData):
|
||||
let (flags, startDate, joinedTooEarlyDate, adminDisallowedChatId, disallowedCountry) = (giveawayInfoData.flags, giveawayInfoData.startDate, giveawayInfoData.joinedTooEarlyDate, giveawayInfoData.adminDisallowedChatId, giveawayInfoData.disallowedCountry)
|
||||
if (flags & (1 << 3)) != 0 {
|
||||
return .ongoing(startDate: startDate, status: .almostOver)
|
||||
} else if (flags & (1 << 0)) != 0 {
|
||||
@@ -128,7 +129,8 @@ func _internal_getPremiumGiveawayInfo(account: Account, peerId: EnginePeer.Id, m
|
||||
} else {
|
||||
return .ongoing(startDate: startDate, status: .notQualified)
|
||||
}
|
||||
case let .giveawayInfoResults(flags, startDate, giftCodeSlug, stars, finishDate, winnersCount, activatedCount):
|
||||
case let .giveawayInfoResults(giveawayInfoResultsData):
|
||||
let (flags, startDate, giftCodeSlug, stars, finishDate, winnersCount, activatedCount) = (giveawayInfoResultsData.flags, giveawayInfoResultsData.startDate, giveawayInfoResultsData.giftCodeSlug, giveawayInfoResultsData.starsPrize, giveawayInfoResultsData.finishDate, giveawayInfoResultsData.winnersCount, giveawayInfoResultsData.activatedCount)
|
||||
let status: PremiumGiveawayInfo.ResultStatus
|
||||
if (flags & (1 << 1)) != 0 {
|
||||
status = .refunded
|
||||
@@ -270,7 +272,8 @@ func _internal_checkPremiumGiftCode(account: Account, slug: String) -> Signal<Pr
|
||||
|> mapToSignal { result -> Signal<PremiumGiftCodeInfo?, NoError> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .checkedGiftCode(_, _, _, _, _, _, _, chats, users):
|
||||
case let .checkedGiftCode(checkedGiftCodeData):
|
||||
let (chats, users) = (checkedGiftCodeData.chats, checkedGiftCodeData.users)
|
||||
return account.postbox.transaction { transaction in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers)
|
||||
@@ -349,9 +352,9 @@ func _internal_launchPrepaidGiveaway(account: Account, peerId: EnginePeer.Id, pu
|
||||
let inputPurpose: Api.InputStorePaymentPurpose
|
||||
switch purpose {
|
||||
case let .stars(stars, users):
|
||||
inputPurpose = .inputStorePaymentStarsGiveaway(flags: flags, stars: stars, boostPeer: inputPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: "", amount: 0, users: users)
|
||||
inputPurpose = .inputStorePaymentStarsGiveaway(.init(flags: flags, stars: stars, boostPeer: inputPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: "", amount: 0, users: users))
|
||||
case .premium:
|
||||
inputPurpose = .inputStorePaymentPremiumGiveaway(flags: flags, boostPeer: inputPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: "", amount: 0)
|
||||
inputPurpose = .inputStorePaymentPremiumGiveaway(.init(flags: flags, boostPeer: inputPeer, additionalPeers: additionalPeers, countriesIso2: countries, prizeDescription: prizeDescription, randomId: randomId, untilDate: untilDate, currency: "", amount: 0))
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.payments.launchPrepaidGiveaway(peer: inputPeer, giveawayId: id, purpose: inputPurpose))
|
||||
@@ -370,7 +373,8 @@ func _internal_launchPrepaidGiveaway(account: Account, peerId: EnginePeer.Id, pu
|
||||
extension PremiumGiftCodeOption {
|
||||
init(apiGiftCodeOption: Api.PremiumGiftCodeOption) {
|
||||
switch apiGiftCodeOption {
|
||||
case let .premiumGiftCodeOption(_, users, months, storeProduct, storeQuantity, curreny, amount):
|
||||
case let .premiumGiftCodeOption(premiumGiftCodeOptionData):
|
||||
let (_, users, months, storeProduct, storeQuantity, curreny, amount) = (premiumGiftCodeOptionData.flags, premiumGiftCodeOptionData.users, premiumGiftCodeOptionData.months, premiumGiftCodeOptionData.storeProduct, premiumGiftCodeOptionData.storeQuantity, premiumGiftCodeOptionData.currency, premiumGiftCodeOptionData.amount)
|
||||
self.init(users: users, months: months, storeProductId: storeProduct, storeQuantity: storeQuantity ?? 1, currency: curreny, amount: amount)
|
||||
}
|
||||
}
|
||||
@@ -379,7 +383,8 @@ extension PremiumGiftCodeOption {
|
||||
extension PremiumGiftCodeInfo {
|
||||
init(apiCheckedGiftCode: Api.payments.CheckedGiftCode, slug: String) {
|
||||
switch apiCheckedGiftCode {
|
||||
case let .checkedGiftCode(flags, fromId, giveawayMsgId, toId, date, months, usedDate, _, _):
|
||||
case let .checkedGiftCode(checkedGiftCodeData):
|
||||
let (flags, fromId, giveawayMsgId, toId, date, months, usedDate) = (checkedGiftCodeData.flags, checkedGiftCodeData.fromId, checkedGiftCodeData.giveawayMsgId, checkedGiftCodeData.toId, checkedGiftCodeData.date, checkedGiftCodeData.days, checkedGiftCodeData.usedDate)
|
||||
self.slug = slug
|
||||
self.fromPeerId = fromId?.peerId
|
||||
if let fromId = fromId, let giveawayMsgId = giveawayMsgId {
|
||||
@@ -405,12 +410,14 @@ public extension PremiumGiftCodeInfo {
|
||||
extension PrepaidGiveaway {
|
||||
init(apiPrepaidGiveaway: Api.PrepaidGiveaway) {
|
||||
switch apiPrepaidGiveaway {
|
||||
case let .prepaidGiveaway(id, months, quantity, date):
|
||||
case let .prepaidGiveaway(prepaidGiveawayData):
|
||||
let (id, months, quantity, date) = (prepaidGiveawayData.id, prepaidGiveawayData.months, prepaidGiveawayData.quantity, prepaidGiveawayData.date)
|
||||
self.id = id
|
||||
self.prize = .premium(months: months)
|
||||
self.quantity = quantity
|
||||
self.date = date
|
||||
case let .prepaidStarsGiveaway(id, stars, quantity, boosts, date):
|
||||
case let .prepaidStarsGiveaway(prepaidStarsGiveawayData):
|
||||
let (id, stars, quantity, boosts, date) = (prepaidStarsGiveawayData.id, prepaidStarsGiveawayData.stars, prepaidStarsGiveawayData.quantity, prepaidStarsGiveawayData.boosts, prepaidStarsGiveawayData.date)
|
||||
self.id = id
|
||||
self.prize = .stars(stars: stars, boosts: boosts)
|
||||
self.quantity = quantity
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,9 +11,9 @@ public enum StarGiftAuctionReference: Equatable {
|
||||
var apiAuction: Api.InputStarGiftAuction {
|
||||
switch self {
|
||||
case let .giftId(giftId):
|
||||
return .inputStarGiftAuction(giftId: giftId)
|
||||
return .inputStarGiftAuction(.init(giftId: giftId))
|
||||
case let .slug(slug):
|
||||
return .inputStarGiftAuctionSlug(slug: slug)
|
||||
return .inputStarGiftAuctionSlug(.init(slug: slug))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,8 @@ private func _internal_getStarGiftAuctionState(postbox: Postbox, network: Networ
|
||||
}
|
||||
return postbox.transaction { transaction -> (gift: StarGift, state: GiftAuctionContext.State.AuctionState?, myState: GiftAuctionContext.State.MyState, timeout: Int32)? in
|
||||
switch result {
|
||||
case let .starGiftAuctionState(apiGift, state, userState, timeout, users, chats):
|
||||
case let .starGiftAuctionState(starGiftAuctionStateData):
|
||||
let (apiGift, state, userState, timeout, users, chats) = (starGiftAuctionStateData.gift, starGiftAuctionStateData.state, starGiftAuctionStateData.userState, starGiftAuctionStateData.timeout, starGiftAuctionStateData.users, starGiftAuctionStateData.chats)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(chats: chats, users: users))
|
||||
guard let gift = StarGift(apiStarGift: apiGift) else {
|
||||
return nil
|
||||
@@ -242,7 +243,8 @@ public final class GiftAuctionContext {
|
||||
extension GiftAuctionContext.State.BidLevel {
|
||||
init(apiBidLevel: Api.AuctionBidLevel) {
|
||||
switch apiBidLevel {
|
||||
case let .auctionBidLevel(pos, amount, date):
|
||||
case let .auctionBidLevel(auctionBidLevelData):
|
||||
let (pos, amount, date) = (auctionBidLevelData.pos, auctionBidLevelData.amount, auctionBidLevelData.date)
|
||||
self.position = pos
|
||||
self.amount = amount
|
||||
self.date = date
|
||||
@@ -253,7 +255,8 @@ extension GiftAuctionContext.State.BidLevel {
|
||||
extension GiftAuctionContext.State.AuctionState {
|
||||
init?(apiAuctionState: Api.StarGiftAuctionState, peers: [PeerId: Peer]) {
|
||||
switch apiAuctionState {
|
||||
case let .starGiftAuctionState(version, startDate, endDate, minBidAmount, bidLevels, topBiddersPeerIds, nextRoundAt, lastGiftNumber, giftsLeft, currentRound, totalRounds, apiRounds):
|
||||
case let .starGiftAuctionState(starGiftAuctionStateData):
|
||||
let (version, startDate, endDate, minBidAmount, bidLevels, topBiddersPeerIds, nextRoundAt, lastGiftNumber, giftsLeft, currentRound, totalRounds, apiRounds) = (starGiftAuctionStateData.version, starGiftAuctionStateData.startDate, starGiftAuctionStateData.endDate, starGiftAuctionStateData.minBidAmount, starGiftAuctionStateData.bidLevels, starGiftAuctionStateData.topBidders, starGiftAuctionStateData.nextRoundAt, starGiftAuctionStateData.lastGiftNum, starGiftAuctionStateData.giftsLeft, starGiftAuctionStateData.currentRound, starGiftAuctionStateData.totalRounds, starGiftAuctionStateData.rounds)
|
||||
var topBidders: [EnginePeer] = []
|
||||
for peerId in topBiddersPeerIds {
|
||||
if let peer = peers[PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(peerId))] {
|
||||
@@ -263,9 +266,11 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
var rounds: [GiftAuctionContext.State.Round] = []
|
||||
for apiRound in apiRounds {
|
||||
switch apiRound {
|
||||
case let .starGiftAuctionRound(num, duration):
|
||||
case let .starGiftAuctionRound(starGiftAuctionRoundData):
|
||||
let (num, duration) = (starGiftAuctionRoundData.num, starGiftAuctionRoundData.duration)
|
||||
rounds.append(.generic(num: num, duration: duration))
|
||||
case let .starGiftAuctionRoundExtendable(num, duration, extendTop, extendWindow):
|
||||
case let .starGiftAuctionRoundExtendable(starGiftAuctionRoundExtendableData):
|
||||
let (num, duration, extendTop, extendWindow) = (starGiftAuctionRoundExtendableData.num, starGiftAuctionRoundExtendableData.duration, starGiftAuctionRoundExtendableData.extendTop, starGiftAuctionRoundExtendableData.extendWindow)
|
||||
rounds.append(.extendable(num: num, duration: duration, extendTop: extendTop, extendWindow: extendWindow))
|
||||
}
|
||||
}
|
||||
@@ -283,7 +288,8 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
rounds: rounds,
|
||||
lastGiftNumber: lastGiftNumber
|
||||
)
|
||||
case let .starGiftAuctionStateFinished(_, startDate, endDate, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl):
|
||||
case let .starGiftAuctionStateFinished(starGiftAuctionStateFinishedData):
|
||||
let (startDate, endDate, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl) = (starGiftAuctionStateFinishedData.startDate, starGiftAuctionStateFinishedData.endDate, starGiftAuctionStateFinishedData.averagePrice, starGiftAuctionStateFinishedData.listedCount, starGiftAuctionStateFinishedData.fragmentListedCount, starGiftAuctionStateFinishedData.fragmentListedUrl)
|
||||
self = .finished(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
@@ -296,10 +302,11 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
init?(apiAuctionState: Api.StarGiftAuctionState, transaction: Transaction) {
|
||||
switch apiAuctionState {
|
||||
case let .starGiftAuctionState(version, startDate, endDate, minBidAmount, bidLevels, topBiddersPeerIds, nextRoundAt, lastGiftNumber, giftsLeft, currentRound, totalRounds, apiRounds):
|
||||
case let .starGiftAuctionState(starGiftAuctionStateData):
|
||||
let (version, startDate, endDate, minBidAmount, bidLevels, topBiddersPeerIds, nextRoundAt, lastGiftNumber, giftsLeft, currentRound, totalRounds, apiRounds) = (starGiftAuctionStateData.version, starGiftAuctionStateData.startDate, starGiftAuctionStateData.endDate, starGiftAuctionStateData.minBidAmount, starGiftAuctionStateData.bidLevels, starGiftAuctionStateData.topBidders, starGiftAuctionStateData.nextRoundAt, starGiftAuctionStateData.lastGiftNum, starGiftAuctionStateData.giftsLeft, starGiftAuctionStateData.currentRound, starGiftAuctionStateData.totalRounds, starGiftAuctionStateData.rounds)
|
||||
var topBidders: [EnginePeer] = []
|
||||
for peerId in topBiddersPeerIds {
|
||||
if let peer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(peerId))) {
|
||||
@@ -309,9 +316,11 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
var rounds: [GiftAuctionContext.State.Round] = []
|
||||
for apiRound in apiRounds {
|
||||
switch apiRound {
|
||||
case let .starGiftAuctionRound(num, duration):
|
||||
case let .starGiftAuctionRound(starGiftAuctionRoundData):
|
||||
let (num, duration) = (starGiftAuctionRoundData.num, starGiftAuctionRoundData.duration)
|
||||
rounds.append(.generic(num: num, duration: duration))
|
||||
case let .starGiftAuctionRoundExtendable(num, duration, extendTop, extendWindow):
|
||||
case let .starGiftAuctionRoundExtendable(starGiftAuctionRoundExtendableData):
|
||||
let (num, duration, extendTop, extendWindow) = (starGiftAuctionRoundExtendableData.num, starGiftAuctionRoundExtendableData.duration, starGiftAuctionRoundExtendableData.extendTop, starGiftAuctionRoundExtendableData.extendWindow)
|
||||
rounds.append(.extendable(num: num, duration: duration, extendTop: extendTop, extendWindow: extendWindow))
|
||||
}
|
||||
}
|
||||
@@ -329,7 +338,8 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
rounds: rounds,
|
||||
lastGiftNumber: lastGiftNumber
|
||||
)
|
||||
case let .starGiftAuctionStateFinished(_, startDate, endDate, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl):
|
||||
case let .starGiftAuctionStateFinished(starGiftAuctionStateFinishedData):
|
||||
let (startDate, endDate, averagePrice, listedCount, fragmentListedCount, fragmentListedUrl) = (starGiftAuctionStateFinishedData.startDate, starGiftAuctionStateFinishedData.endDate, starGiftAuctionStateFinishedData.averagePrice, starGiftAuctionStateFinishedData.listedCount, starGiftAuctionStateFinishedData.fragmentListedCount, starGiftAuctionStateFinishedData.fragmentListedUrl)
|
||||
self = .finished(
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
@@ -347,7 +357,8 @@ extension GiftAuctionContext.State.AuctionState {
|
||||
extension GiftAuctionContext.State.MyState {
|
||||
init(apiAuctionUserState: Api.StarGiftAuctionUserState) {
|
||||
switch apiAuctionUserState {
|
||||
case let .starGiftAuctionUserState(flags, bidAmount, bidDate, minBidAmount, bidPeerId, acquiredCount):
|
||||
case let .starGiftAuctionUserState(starGiftAuctionUserStateData):
|
||||
let (flags, bidAmount, bidDate, minBidAmount, bidPeerId, acquiredCount) = (starGiftAuctionUserStateData.flags, starGiftAuctionUserStateData.bidAmount, starGiftAuctionUserStateData.bidDate, starGiftAuctionUserStateData.minBidAmount, starGiftAuctionUserStateData.bidPeer, starGiftAuctionUserStateData.acquiredCount)
|
||||
self.isReturned = (flags & (1 << 1)) != 0
|
||||
self.bidAmount = bidAmount
|
||||
self.bidDate = bidDate
|
||||
@@ -382,19 +393,22 @@ func _internal_getGiftAuctionAcquiredGifts(account: Account, giftId: Int64) -> S
|
||||
}
|
||||
return account.postbox.transaction { transaction -> [GiftAuctionAcquiredGift] in
|
||||
switch result {
|
||||
case let .starGiftAuctionAcquiredGifts(gifts, users, chats):
|
||||
case let .starGiftAuctionAcquiredGifts(starGiftAuctionAcquiredGiftsData):
|
||||
let (gifts, users, chats) = (starGiftAuctionAcquiredGiftsData.gifts, starGiftAuctionAcquiredGiftsData.users, starGiftAuctionAcquiredGiftsData.chats)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers)
|
||||
|
||||
var mappedGifts: [GiftAuctionAcquiredGift] = []
|
||||
for gift in gifts {
|
||||
switch gift {
|
||||
case let .starGiftAuctionAcquiredGift(flags, peerId, date, bidAmount, round, pos, message, number):
|
||||
case let .starGiftAuctionAcquiredGift(starGiftAuctionAcquiredGiftData):
|
||||
let (flags, peerId, date, bidAmount, round, pos, message, number) = (starGiftAuctionAcquiredGiftData.flags, starGiftAuctionAcquiredGiftData.peer, starGiftAuctionAcquiredGiftData.date, starGiftAuctionAcquiredGiftData.bidAmount, starGiftAuctionAcquiredGiftData.round, starGiftAuctionAcquiredGiftData.pos, starGiftAuctionAcquiredGiftData.message, starGiftAuctionAcquiredGiftData.giftNum)
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
var text: String?
|
||||
var entities: [MessageTextEntity]?
|
||||
switch message {
|
||||
case let .textWithEntities(textValue, entitiesValue):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (textValue, entitiesValue) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
text = textValue
|
||||
entities = messageTextEntitiesFromApiEntities(entitiesValue)
|
||||
default:
|
||||
@@ -426,14 +440,16 @@ func _internal_getActiveGiftAuctions(account: Account, hash: Int64) -> Signal<[G
|
||||
|> mapToSignal { result in
|
||||
return account.postbox.transaction { transaction -> [GiftAuctionContext]? in
|
||||
switch result {
|
||||
case let .starGiftActiveAuctions(auctions, users, chats):
|
||||
case let .starGiftActiveAuctions(starGiftActiveAuctionsData):
|
||||
let (auctions, users, chats) = (starGiftActiveAuctionsData.auctions, starGiftActiveAuctionsData.users, starGiftActiveAuctionsData.chats)
|
||||
let parsedPeers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers)
|
||||
|
||||
var auctionContexts: [GiftAuctionContext] = []
|
||||
for auction in auctions {
|
||||
switch auction {
|
||||
case let .starGiftActiveAuctionState(apiGift, auctionState, userState):
|
||||
case let .starGiftActiveAuctionState(starGiftActiveAuctionStateData):
|
||||
let (apiGift, auctionState, userState) = (starGiftActiveAuctionStateData.gift, starGiftActiveAuctionStateData.state, starGiftActiveAuctionStateData.userState)
|
||||
guard let gift = StarGift(apiStarGift: apiGift) else {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -42,7 +42,13 @@ public struct StarGiftCollection: Codable, Equatable {
|
||||
extension StarGiftCollection {
|
||||
init?(apiStarGiftCollection: Api.StarGiftCollection) {
|
||||
switch apiStarGiftCollection {
|
||||
case let .starGiftCollection(_, collectionId, title, icon, giftsCount, hash):
|
||||
case let .starGiftCollection(starGiftCollectionData):
|
||||
let _ = starGiftCollectionData.flags
|
||||
let collectionId = starGiftCollectionData.collectionId
|
||||
let title = starGiftCollectionData.title
|
||||
let icon = starGiftCollectionData.icon
|
||||
let giftsCount = starGiftCollectionData.giftsCount
|
||||
let hash = starGiftCollectionData.hash
|
||||
self.id = collectionId
|
||||
self.title = title
|
||||
self.icon = icon.flatMap { telegramMediaFileFromApiDocument($0, altDocuments: nil) }
|
||||
@@ -121,8 +127,9 @@ private func _internal_getStarGiftCollections(postbox: Postbox, network: Network
|
||||
}
|
||||
return postbox.transaction { transaction -> [StarGiftCollection]? in
|
||||
switch result {
|
||||
case let .starGiftCollections(collections):
|
||||
let collections = collections.compactMap { StarGiftCollection(apiStarGiftCollection: $0) }
|
||||
case let .starGiftCollections(starGiftCollectionsData):
|
||||
let apiCollections = starGiftCollectionsData.collections
|
||||
let collections = apiCollections.compactMap { StarGiftCollection(apiStarGiftCollection: $0) }
|
||||
return collections
|
||||
case .starGiftCollectionsNotModified:
|
||||
return cachedCollections ?? []
|
||||
|
||||
@@ -51,7 +51,8 @@ public struct StarsTopUpOption: Equatable, Codable {
|
||||
extension StarsTopUpOption {
|
||||
init(apiStarsTopupOption: Api.StarsTopupOption) {
|
||||
switch apiStarsTopupOption {
|
||||
case let .starsTopupOption(flags, stars, storeProduct, currency, amount):
|
||||
case let .starsTopupOption(starsTopupOptionData):
|
||||
let (flags, stars, storeProduct, currency, amount) = (starsTopupOptionData.flags, starsTopupOptionData.stars, starsTopupOptionData.storeProduct, starsTopupOptionData.currency, starsTopupOptionData.amount)
|
||||
self.init(count: stars, storeProductId: storeProduct, currency: currency, amount: amount, isExtended: (flags & (1 << 1)) != 0)
|
||||
}
|
||||
}
|
||||
@@ -117,7 +118,8 @@ public struct StarsGiftOption: Equatable, Codable {
|
||||
extension StarsGiftOption {
|
||||
init(apiStarsGiftOption: Api.StarsGiftOption) {
|
||||
switch apiStarsGiftOption {
|
||||
case let .starsGiftOption(flags, stars, storeProduct, currency, amount):
|
||||
case let .starsGiftOption(starsGiftOptionData):
|
||||
let (flags, stars, storeProduct, currency, amount) = (starsGiftOptionData.flags, starsGiftOptionData.stars, starsGiftOptionData.storeProduct, starsGiftOptionData.currency, starsGiftOptionData.amount)
|
||||
self.init(count: stars, storeProductId: storeProduct, currency: currency, amount: amount, isExtended: (flags & (1 << 1)) != 0)
|
||||
}
|
||||
}
|
||||
@@ -241,7 +243,8 @@ public struct StarsGiveawayOption: Equatable, Codable {
|
||||
extension StarsGiveawayOption.Winners {
|
||||
init(apiStarsGiveawayWinnersOption: Api.StarsGiveawayWinnersOption) {
|
||||
switch apiStarsGiveawayWinnersOption {
|
||||
case let .starsGiveawayWinnersOption(flags, users, starsPerUser):
|
||||
case let .starsGiveawayWinnersOption(starsGiveawayWinnersOptionData):
|
||||
let (flags, users, starsPerUser) = (starsGiveawayWinnersOptionData.flags, starsGiveawayWinnersOptionData.users, starsGiveawayWinnersOptionData.perUserStars)
|
||||
self.init(users: users, starsPerUser: starsPerUser, isDefault: (flags & (1 << 0)) != 0)
|
||||
}
|
||||
}
|
||||
@@ -250,7 +253,8 @@ extension StarsGiveawayOption.Winners {
|
||||
extension StarsGiveawayOption {
|
||||
init(apiStarsGiveawayOption: Api.StarsGiveawayOption) {
|
||||
switch apiStarsGiveawayOption {
|
||||
case let .starsGiveawayOption(flags, stars, yearlyBoosts, storeProduct, currency, amount, winners):
|
||||
case let .starsGiveawayOption(starsGiveawayOptionData):
|
||||
let (flags, stars, yearlyBoosts, storeProduct, currency, amount, winners) = (starsGiveawayOptionData.flags, starsGiveawayOptionData.stars, starsGiveawayOptionData.yearlyBoosts, starsGiveawayOptionData.storeProduct, starsGiveawayOptionData.currency, starsGiveawayOptionData.amount, starsGiveawayOptionData.winners)
|
||||
self.init(count: stars, yearlyBoosts: yearlyBoosts, storeProductId: storeProduct, currency: currency, amount: amount, winners: winners.map { StarsGiveawayOption.Winners(apiStarsGiveawayWinnersOption: $0) }, isExtended: (flags & (1 << 0)) != 0, isDefault: (flags & (1 << 1)) != 0)
|
||||
}
|
||||
}
|
||||
@@ -346,9 +350,11 @@ public struct StarsAmount: Equatable, Comparable, Hashable, Codable, CustomStrin
|
||||
extension StarsAmount {
|
||||
init(apiAmount: Api.StarsAmount) {
|
||||
switch apiAmount {
|
||||
case let .starsAmount(amount, nanos):
|
||||
case let .starsAmount(starsAmountData):
|
||||
let (amount, nanos) = (starsAmountData.amount, starsAmountData.nanos)
|
||||
self.init(value: amount, nanos: nanos)
|
||||
case let .starsTonAmount(amount):
|
||||
case let .starsTonAmount(starsTonAmountData):
|
||||
let amount = starsTonAmountData.amount
|
||||
self.init(value: amount, nanos: 0)
|
||||
}
|
||||
}
|
||||
@@ -389,9 +395,11 @@ public struct CurrencyAmount: Equatable, Hashable, Codable {
|
||||
extension CurrencyAmount {
|
||||
init(apiAmount: Api.StarsAmount) {
|
||||
switch apiAmount {
|
||||
case let .starsAmount(amount, nanos):
|
||||
case let .starsAmount(starsAmountData):
|
||||
let (amount, nanos) = (starsAmountData.amount, starsAmountData.nanos)
|
||||
self.init(amount: StarsAmount(value: amount, nanos: nanos), currency: .stars)
|
||||
case let .starsTonAmount(amount):
|
||||
case let .starsTonAmount(starsTonAmountData):
|
||||
let amount = starsTonAmountData.amount
|
||||
self.init(amount: StarsAmount(value: amount, nanos: 0), currency: .ton)
|
||||
}
|
||||
}
|
||||
@@ -399,10 +407,10 @@ extension CurrencyAmount {
|
||||
var apiAmount: Api.StarsAmount {
|
||||
switch self.currency {
|
||||
case .stars:
|
||||
return .starsAmount(amount: self.amount.value, nanos: self.amount.nanos)
|
||||
return .starsAmount(.init(amount: self.amount.value, nanos: self.amount.nanos))
|
||||
case .ton:
|
||||
assert(self.amount.nanos == 0)
|
||||
return .starsTonAmount(amount: self.amount.value)
|
||||
return .starsTonAmount(.init(amount: self.amount.value))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -462,7 +470,8 @@ private func _internal_requestStarsState(account: Account, peerId: EnginePeer.Id
|
||||
|> mapToSignal { result -> Signal<InternalStarsStatus, RequestStarsStateError> in
|
||||
return account.postbox.transaction { transaction -> InternalStarsStatus in
|
||||
switch result {
|
||||
case let .starsStatus(_, balance, _, _, subscriptionsMissingBalance, transactions, nextTransactionsOffset, chats, users):
|
||||
case let .starsStatus(starsStatusData):
|
||||
let (_, balance, _, _, subscriptionsMissingBalance, transactions, nextTransactionsOffset, chats, users) = (starsStatusData.flags, starsStatusData.balance, starsStatusData.subscriptions, starsStatusData.subscriptionsNextOffset, starsStatusData.subscriptionsMissingBalance, starsStatusData.history, starsStatusData.nextOffset, starsStatusData.chats, starsStatusData.users)
|
||||
let peers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: peers)
|
||||
|
||||
@@ -515,10 +524,11 @@ private func _internal_requestStarsSubscriptions(account: Account, peerId: Engin
|
||||
}
|
||||
return account.postbox.transaction { transaction -> InternalStarsStatus in
|
||||
switch result {
|
||||
case let .starsStatus(_, balance, subscriptions, subscriptionsNextOffset, subscriptionsMissingBalance, _, _, chats, users):
|
||||
case let .starsStatus(starsStatusData):
|
||||
let (_, balance, subscriptions, subscriptionsNextOffset, subscriptionsMissingBalance, _, _, chats, users) = (starsStatusData.flags, starsStatusData.balance, starsStatusData.subscriptions, starsStatusData.subscriptionsNextOffset, starsStatusData.subscriptionsMissingBalance, starsStatusData.history, starsStatusData.nextOffset, starsStatusData.chats, starsStatusData.users)
|
||||
let peers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: peers)
|
||||
|
||||
|
||||
var parsedSubscriptions: [StarsContext.State.Subscription] = []
|
||||
if let subscriptions {
|
||||
for entry in subscriptions {
|
||||
@@ -655,11 +665,12 @@ private final class StarsContextImpl {
|
||||
private extension StarsContext.State.Transaction {
|
||||
init?(apiTransaction: Api.StarsTransaction, peerId: EnginePeer.Id?, transaction: Transaction) {
|
||||
switch apiTransaction {
|
||||
case let .starsTransaction(apiFlags, id, stars, date, transactionPeer, title, description, photo, transactionDate, transactionUrl, _, messageId, extendedMedia, subscriptionPeriod, giveawayPostId, starGift, floodskipNumber, starrefCommissionPermille, starrefPeer, starrefAmount, paidMessageCount, premiumGiftMonths, adsProceedsFromDate, adsProceedsToDate):
|
||||
case let .starsTransaction(starsTransactionData):
|
||||
let (apiFlags, id, stars, date, transactionPeer, title, description, photo, transactionDate, transactionUrl, _, messageId, extendedMedia, subscriptionPeriod, giveawayPostId, starGift, floodskipNumber, starrefCommissionPermille, starrefPeer, starrefAmount, paidMessageCount, premiumGiftMonths, adsProceedsFromDate, adsProceedsToDate) = (starsTransactionData.flags, starsTransactionData.id, starsTransactionData.amount, starsTransactionData.date, starsTransactionData.peer, starsTransactionData.title, starsTransactionData.description, starsTransactionData.photo, starsTransactionData.transactionDate, starsTransactionData.transactionUrl, starsTransactionData.botPayload, starsTransactionData.msgId, starsTransactionData.extendedMedia, starsTransactionData.subscriptionPeriod, starsTransactionData.giveawayPostId, starsTransactionData.stargift, starsTransactionData.floodskipNumber, starsTransactionData.starrefCommissionPermille, starsTransactionData.starrefPeer, starsTransactionData.starrefAmount, starsTransactionData.paidMessages, starsTransactionData.premiumGiftMonths, starsTransactionData.adsProceedsFromDate, starsTransactionData.adsProceedsToDate)
|
||||
let parsedPeer: StarsContext.State.Transaction.Peer
|
||||
var paidMessageId: MessageId?
|
||||
var giveawayMessageId: MessageId?
|
||||
|
||||
|
||||
switch transactionPeer {
|
||||
case .starsTransactionPeerAppStore:
|
||||
parsedPeer = .appStore
|
||||
@@ -675,7 +686,8 @@ private extension StarsContext.State.Transaction {
|
||||
parsedPeer = .apiLimitExtension
|
||||
case .starsTransactionPeerUnsupported:
|
||||
parsedPeer = .unsupported
|
||||
case let .starsTransactionPeer(apiPeer):
|
||||
case let .starsTransactionPeer(starsTransactionPeerData):
|
||||
let apiPeer = starsTransactionPeerData.peer
|
||||
guard let peer = transaction.getPeer(apiPeer.peerId) else {
|
||||
return nil
|
||||
}
|
||||
@@ -749,7 +761,8 @@ private extension StarsContext.State.Transaction {
|
||||
private extension StarsContext.State.Subscription {
|
||||
init?(apiSubscription: Api.StarsSubscription, transaction: Transaction) {
|
||||
switch apiSubscription {
|
||||
case let .starsSubscription(apiFlags, id, apiPeer, untilDate, pricing, inviteHash, title, photo, invoiceSlug):
|
||||
case let .starsSubscription(starsSubscriptionData):
|
||||
let (apiFlags, id, apiPeer, untilDate, pricing, inviteHash, title, photo, invoiceSlug) = (starsSubscriptionData.flags, starsSubscriptionData.id, starsSubscriptionData.peer, starsSubscriptionData.untilDate, starsSubscriptionData.pricing, starsSubscriptionData.chatInviteHash, starsSubscriptionData.title, starsSubscriptionData.photo, starsSubscriptionData.invoiceSlug)
|
||||
guard let peer = transaction.getPeer(apiPeer.peerId) else {
|
||||
return nil
|
||||
}
|
||||
@@ -1591,7 +1604,8 @@ func _internal_sendStarsPaymentForm(account: Account, formId: Int64, source: Bot
|
||||
return account.network.request(Api.functions.payments.sendStarsForm(formId: formId, invoice: invoice))
|
||||
|> map { result -> SendBotPaymentResult in
|
||||
switch result {
|
||||
case let .paymentResult(updates):
|
||||
case let .paymentResult(paymentResultData):
|
||||
let updates = paymentResultData.updates
|
||||
account.stateManager.addUpdates(updates)
|
||||
|
||||
switch source {
|
||||
@@ -1644,7 +1658,7 @@ func _internal_sendStarsPaymentForm(account: Account, formId: Int64, source: Bot
|
||||
case .giftCode, .stars, .starsGift, .starsChatSubscription, .starGift, .starGiftUpgrade, .starGiftTransfer, .premiumGift, .starGiftResale, .starGiftPrepaidUpgrade, .starGiftDropOriginalDetails, .starGiftAuctionBid:
|
||||
receiptMessageId = nil
|
||||
}
|
||||
} else if case let .starGiftUnique(gift, _, _, savedToProfile, canExportDate, transferStars, isRefunded, _, peerId, _, savedId, _, canTransferDate, canResaleDate, dropOriginalDetailsStars, _, _) = action.action, case let .Id(messageId) = message.id {
|
||||
} else if case let .starGiftUnique(gift, _, _, savedToProfile, canExportDate, transferStars, isRefunded, _, peerId, _, savedId, _, canTransferDate, canResaleDate, dropOriginalDetailsStars, _, _, canCraftAt, _) = action.action, case let .Id(messageId) = message.id {
|
||||
let reference: StarGiftReference
|
||||
if let peerId, let savedId {
|
||||
reference = .peer(peerId: peerId, id: savedId)
|
||||
@@ -1673,7 +1687,8 @@ func _internal_sendStarsPaymentForm(account: Account, formId: Int64, source: Bot
|
||||
upgradeSeparate: false,
|
||||
dropOriginalDetailsStars: dropOriginalDetailsStars,
|
||||
number: nil,
|
||||
isRefunded: isRefunded
|
||||
isRefunded: isRefunded,
|
||||
canCraftAt: canCraftAt
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1681,7 +1696,8 @@ func _internal_sendStarsPaymentForm(account: Account, formId: Int64, source: Bot
|
||||
}
|
||||
}
|
||||
return .done(receiptMessageId: receiptMessageId, subscriptionPeerId: nil, uniqueStarGift: resultGift)
|
||||
case let .paymentVerificationNeeded(url):
|
||||
case let .paymentVerificationNeeded(paymentVerificationNeededData):
|
||||
let url = paymentVerificationNeededData.url
|
||||
return .externalVerificationRequired(url: url)
|
||||
}
|
||||
}
|
||||
@@ -1746,7 +1762,7 @@ func _internal_getStarsTransaction(accountPeerId: PeerId, postbox: Postbox, netw
|
||||
Api.functions.payments.getStarsTransactionsByID(
|
||||
flags: transactionReference.ton ? 1 << 0 : 0,
|
||||
peer: inputPeer,
|
||||
id: [.inputStarsTransaction(flags: transactionReference.isRefund ? (1 << 0) : 0, id: transactionReference.id)]
|
||||
id: [.inputStarsTransaction(.init(flags: transactionReference.isRefund ? (1 << 0) : 0, id: transactionReference.id))]
|
||||
)
|
||||
)
|
||||
|> map(Optional.init)
|
||||
@@ -1755,9 +1771,11 @@ func _internal_getStarsTransaction(accountPeerId: PeerId, postbox: Postbox, netw
|
||||
}
|
||||
|> mapToSignal { result -> Signal<StarsContext.State.Transaction?, NoError> in
|
||||
return postbox.transaction { transaction -> StarsContext.State.Transaction? in
|
||||
guard let result, case let .starsStatus(_, _, _, _, _, transactions, _, chats, users) = result, let matchingTransaction = transactions?.first else {
|
||||
guard let result, case let .starsStatus(starsStatusData) = result, let matchingTransaction = starsStatusData.history?.first else {
|
||||
return nil
|
||||
}
|
||||
let (_, _, _, _, _, transactions, _, chats, users) = (starsStatusData.flags, starsStatusData.balance, starsStatusData.subscriptions, starsStatusData.subscriptionsNextOffset, starsStatusData.subscriptionsMissingBalance, starsStatusData.history, starsStatusData.nextOffset, starsStatusData.chats, starsStatusData.users)
|
||||
let _ = transactions
|
||||
let peers = AccumulatedPeers(chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: peers)
|
||||
|
||||
@@ -1808,13 +1826,14 @@ public struct StarsSubscriptionPricing: Codable, Equatable {
|
||||
extension StarsSubscriptionPricing {
|
||||
init(apiStarsSubscriptionPricing: Api.StarsSubscriptionPricing) {
|
||||
switch apiStarsSubscriptionPricing {
|
||||
case let .starsSubscriptionPricing(period, amount):
|
||||
case let .starsSubscriptionPricing(starsSubscriptionPricingData):
|
||||
let (period, amount) = (starsSubscriptionPricingData.period, starsSubscriptionPricingData.amount)
|
||||
self = .init(period: period, amount: StarsAmount(value: amount, nanos: 0))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var apiStarsSubscriptionPricing: Api.StarsSubscriptionPricing {
|
||||
return .starsSubscriptionPricing(period: self.period, amount: self.amount.value)
|
||||
return .starsSubscriptionPricing(.init(period: self.period, amount: self.amount.value))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ public extension TelegramEngine {
|
||||
return _internal_checkCanSendStarGift(account: self.account, giftId: giftId)
|
||||
}
|
||||
|
||||
public func getUniqueStarGift(slug: String) -> Signal<StarGift.UniqueGift?, NoError> {
|
||||
public func getUniqueStarGift(slug: String) -> Signal<StarGift.UniqueGift, GetUniqueStarGiftError> {
|
||||
return _internal_getUniqueStarGift(account: self.account, slug: slug)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,8 @@ func _internal_searchAdPeers(account: Account, query: String) -> Signal<[AdPeer]
|
||||
}
|
||||
return account.postbox.transaction { transaction -> [AdPeer] in
|
||||
switch result {
|
||||
case let .sponsoredPeers(peers, chats, users):
|
||||
case let .sponsoredPeers(sponsoredPeersData):
|
||||
let (peers, chats, users) = (sponsoredPeersData.peers, sponsoredPeersData.chats, sponsoredPeersData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers)
|
||||
|
||||
@@ -58,7 +59,8 @@ func _internal_searchAdPeers(account: Account, query: String) -> Signal<[AdPeer]
|
||||
for chat in chats {
|
||||
if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
}
|
||||
@@ -71,7 +73,8 @@ func _internal_searchAdPeers(account: Account, query: String) -> Signal<[AdPeer]
|
||||
var result: [AdPeer] = []
|
||||
for peer in peers {
|
||||
switch peer {
|
||||
case let .sponsoredPeer(_, randomId, apiPeer, sponsorInfo, additionalInfo):
|
||||
case let .sponsoredPeer(sponsoredPeerData):
|
||||
let (randomId, apiPeer, sponsorInfo, additionalInfo) = (sponsoredPeerData.randomId, sponsoredPeerData.peer, sponsoredPeerData.sponsorInfo, sponsoredPeerData.additionalInfo)
|
||||
guard let peer = parsedPeers.get(apiPeer.peerId) else {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@ func _internal_addGroupMember(account: Account, peerId: PeerId, memberId: PeerId
|
||||
let updatesValue: Api.Updates
|
||||
let missingInviteesValue: [Api.MissingInvitee]
|
||||
switch result {
|
||||
case let .invitedUsers(updates, missingInvitees):
|
||||
case let .invitedUsers(invitedUsersData):
|
||||
let (updates, missingInvitees) = (invitedUsersData.updates, invitedUsersData.missingInvitees)
|
||||
updatesValue = updates
|
||||
missingInviteesValue = missingInvitees
|
||||
}
|
||||
@@ -102,7 +103,8 @@ func _internal_addGroupMember(account: Account, peerId: PeerId, memberId: PeerId
|
||||
|
||||
let result = TelegramInvitePeersResult(forbiddenPeers: missingInviteesValue.compactMap { invitee -> TelegramForbiddenInvitePeer? in
|
||||
switch invitee {
|
||||
case let .missingInvitee(flags, userId):
|
||||
case let .missingInvitee(missingInviteeData):
|
||||
let (flags, userId) = (missingInviteeData.flags, missingInviteeData.userId)
|
||||
guard let peer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) else {
|
||||
return nil
|
||||
}
|
||||
@@ -188,17 +190,19 @@ func _internal_addChannelMember(account: Account, peerId: PeerId, memberId: Peer
|
||||
|> mapToSignal { result -> Signal<(ChannelParticipant?, RenderedChannelParticipant), AddChannelMemberError> in
|
||||
let updatesValue: Api.Updates
|
||||
switch result {
|
||||
case let .invitedUsers(updates, missingInvitees):
|
||||
if case let .missingInvitee(flags, _) = missingInvitees.first {
|
||||
case let .invitedUsers(invitedUsersData):
|
||||
let (updates, missingInvitees) = (invitedUsersData.updates, invitedUsersData.missingInvitees)
|
||||
if case let .missingInvitee(missingInviteeData) = missingInvitees.first {
|
||||
let flags = missingInviteeData.flags
|
||||
let _ = _internal_updateIsPremiumRequiredToContact(account: account, peerIds: [memberPeer.id]).startStandalone()
|
||||
|
||||
|
||||
return .fail(.restricted(TelegramForbiddenInvitePeer(
|
||||
peer: EnginePeer(memberPeer),
|
||||
canInviteWithPremium: (flags & (1 << 0)) != 0,
|
||||
premiumRequiredToContact: (flags & (1 << 1)) != 0
|
||||
)))
|
||||
}
|
||||
|
||||
|
||||
updatesValue = updates
|
||||
}
|
||||
|
||||
@@ -299,7 +303,8 @@ func _internal_addChannelMembers(account: Account, peerId: PeerId, memberIds: [P
|
||||
let updatesValue: Api.Updates
|
||||
let missingInviteesValue: [Api.MissingInvitee]
|
||||
switch result {
|
||||
case let .invitedUsers(updates, missingInvitees):
|
||||
case let .invitedUsers(invitedUsersData):
|
||||
let (updates, missingInvitees) = (invitedUsersData.updates, invitedUsersData.missingInvitees)
|
||||
updatesValue = updates
|
||||
missingInviteesValue = missingInvitees
|
||||
}
|
||||
@@ -310,7 +315,8 @@ func _internal_addChannelMembers(account: Account, peerId: PeerId, memberIds: [P
|
||||
return account.postbox.transaction { transaction -> TelegramInvitePeersResult in
|
||||
let result = TelegramInvitePeersResult(forbiddenPeers: missingInviteesValue.compactMap { invitee -> TelegramForbiddenInvitePeer? in
|
||||
switch invitee {
|
||||
case let .missingInvitee(flags, userId):
|
||||
case let .missingInvitee(missingInviteeData):
|
||||
let (flags, userId) = (missingInviteeData.flags, missingInviteeData.userId)
|
||||
guard let peer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ func _internal_updateAddressName(account: Account, domain: AddressNameDomain, na
|
||||
return .fail(.generic)
|
||||
case let .theme(theme):
|
||||
let flags: Int32 = 1 << 0
|
||||
return account.network.request(Api.functions.account.updateTheme(flags: flags, format: telegramThemeFormat, theme: .inputTheme(id: theme.id, accessHash: theme.accessHash), slug: nil, title: nil, document: nil, settings: nil))
|
||||
return account.network.request(Api.functions.account.updateTheme(flags: flags, format: telegramThemeFormat, theme: .inputTheme(.init(id: theme.id, accessHash: theme.accessHash)), slug: nil, title: nil, document: nil, settings: nil))
|
||||
|> mapError { _ -> UpdateAddressNameError in
|
||||
return .generic
|
||||
}
|
||||
@@ -558,14 +558,17 @@ func _internal_adminedPublicChannels(account: Account, scope: AdminedPublicChann
|
||||
var subscriberCounts: [PeerId: Int] = [:]
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
for chat in apiChats {
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat {
|
||||
if case let .channel(channelData) = chat {
|
||||
let participantsCount = channelData.participantsCount
|
||||
subscriberCounts[chat.peerId] = participantsCount.flatMap(Int.init)
|
||||
}
|
||||
}
|
||||
case let .chatsSlice(_, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let apiChats = chatsSliceData.chats
|
||||
chats = apiChats
|
||||
}
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
@@ -625,9 +628,11 @@ func _internal_channelsForStories(account: Account) -> Signal<[Peer], NoError> {
|
||||
let chats: [Api.Chat]
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
case let .chatsSlice(_, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let apiChats = chatsSliceData.chats
|
||||
chats = apiChats
|
||||
}
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
@@ -637,7 +642,7 @@ func _internal_channelsForStories(account: Account) -> Signal<[Peer], NoError> {
|
||||
if let peer = transaction.getPeer(chat.peerId) {
|
||||
peers.append(peer)
|
||||
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat, let participantsCount = participantsCount {
|
||||
if case let .channel(channelData) = chat, let participantsCount = channelData.participantsCount {
|
||||
transaction.updatePeerCachedData(peerIds: Set([peer.id]), update: { _, current in
|
||||
var current = current as? CachedChannelData ?? CachedChannelData()
|
||||
var participantsSummary = current.participantsSummary
|
||||
@@ -687,9 +692,11 @@ func _internal_channelsForPublicReaction(account: Account, useLocalCache: Bool)
|
||||
let chats: [Api.Chat]
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
case let .chatsSlice(_, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let apiChats = chatsSliceData.chats
|
||||
chats = apiChats
|
||||
}
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
@@ -699,7 +706,7 @@ func _internal_channelsForPublicReaction(account: Account, useLocalCache: Bool)
|
||||
if let peer = transaction.getPeer(chat.peerId) {
|
||||
peers.append(peer)
|
||||
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat, let participantsCount = participantsCount {
|
||||
if case let .channel(channelData) = chat, let participantsCount = channelData.participantsCount {
|
||||
transaction.updatePeerCachedData(peerIds: Set([peer.id]), update: { _, current in
|
||||
var current = current as? CachedChannelData ?? CachedChannelData()
|
||||
var participantsSummary = current.participantsSummary
|
||||
|
||||
@@ -59,7 +59,8 @@ public final class TelegramBirthday: Codable, Equatable {
|
||||
extension TelegramBirthday {
|
||||
convenience init(apiBirthday: Api.Birthday) {
|
||||
switch apiBirthday {
|
||||
case let .birthday(_, day, month, year):
|
||||
case let .birthday(birthdayData):
|
||||
let (_, day, month, year) = (birthdayData.flags, birthdayData.day, birthdayData.month, birthdayData.year)
|
||||
self.init(
|
||||
day: day,
|
||||
month: month,
|
||||
@@ -73,7 +74,7 @@ extension TelegramBirthday {
|
||||
if let _ = self.year {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
return .birthday(flags: flags, day: self.day, month: self.month, year: self.year)
|
||||
return .birthday(Api.Birthday.Cons_birthday(flags: flags, day: self.day, month: self.month, year: self.year))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +118,14 @@ func managedContactBirthdays(stateManager: AccountStateManager) -> Signal<Never,
|
||||
return .complete()
|
||||
}
|
||||
return stateManager.postbox.transaction { transaction -> Void in
|
||||
if case let .contactBirthdays(contactBirthdays, users) = result {
|
||||
if case let .contactBirthdays(contactBirthdaysData) = result {
|
||||
let (contactBirthdays, users) = (contactBirthdaysData.contacts, contactBirthdaysData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: stateManager.accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
var birthdays: [EnginePeer.Id: TelegramBirthday] = [:]
|
||||
for contactBirthday in contactBirthdays {
|
||||
if case let .contactBirthday(contactId, birthday) = contactBirthday {
|
||||
if case let .contactBirthday(contactBirthdayData) = contactBirthday {
|
||||
let (contactId, birthday) = (contactBirthdayData.contactId, contactBirthdayData.birthday)
|
||||
let peerId = EnginePeer.Id(namespace: Namespaces.Peer.CloudUser, id: EnginePeer.Id.Id._internalFromInt64Value(contactId))
|
||||
if peerId == stateManager.accountPeerId {
|
||||
continue
|
||||
|
||||
@@ -65,12 +65,12 @@ func _internal_requestRecommendedBots(account: Account, peerId: EnginePeer.Id, f
|
||||
let parsedPeers: AccumulatedPeers
|
||||
var count: Int32
|
||||
switch result {
|
||||
case let .users(apiUsers):
|
||||
users = apiUsers
|
||||
count = Int32(apiUsers.count)
|
||||
case let .usersSlice(apiCount, apiUsers):
|
||||
users = apiUsers
|
||||
count = apiCount
|
||||
case let .users(usersData):
|
||||
users = usersData.users
|
||||
count = Int32(usersData.users.count)
|
||||
case let .usersSlice(usersSliceData):
|
||||
users = usersSliceData.users
|
||||
count = usersSliceData.count
|
||||
}
|
||||
parsedPeers = AccumulatedPeers(users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: account.peerId, peers: parsedPeers)
|
||||
|
||||
@@ -160,7 +160,7 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
var eventsFilter: Api.ChannelAdminLogEventsFilter? = nil
|
||||
if let filter = filter {
|
||||
flags += Int32(1 << 0)
|
||||
eventsFilter = Api.ChannelAdminLogEventsFilter.channelAdminLogEventsFilter(flags: Int32(filter.rawValue))
|
||||
eventsFilter = Api.ChannelAdminLogEventsFilter.channelAdminLogEventsFilter(Api.ChannelAdminLogEventsFilter.Cons_channelAdminLogEventsFilter(flags: Int32(filter.rawValue)))
|
||||
}
|
||||
if let _ = inputAdmins {
|
||||
flags += Int32(1 << 1)
|
||||
@@ -168,7 +168,8 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
return network.request(Api.functions.channels.getAdminLog(flags: flags, channel: inputChannel, q: query ?? "", eventsFilter: eventsFilter, admins: inputAdmins, maxId: maxId, minId: minId, limit: limit))
|
||||
|> mapToSignal { result in
|
||||
switch result {
|
||||
case let .adminLogResults(apiEvents, apiChats, apiUsers):
|
||||
case let .adminLogResults(adminLogResultsData):
|
||||
let (apiEvents, apiChats, apiUsers) = (adminLogResultsData.events, adminLogResultsData.chats, adminLogResultsData.users)
|
||||
return postbox.transaction { transaction -> AdminLogEventsResult in
|
||||
var peers: [PeerId: Peer] = [:]
|
||||
for apiChat in apiChats {
|
||||
@@ -194,9 +195,11 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
var foundDeletedReplyMessage = false
|
||||
for event in apiEvents {
|
||||
switch event {
|
||||
case let .channelAdminLogEvent(_, _, _, apiAction):
|
||||
case let .channelAdminLogEvent(channelAdminLogEventData):
|
||||
let apiAction = channelAdminLogEventData.action
|
||||
switch apiAction {
|
||||
case let .channelAdminLogEventActionDeleteMessage(apiMessage):
|
||||
case let .channelAdminLogEventActionDeleteMessage(channelAdminLogEventActionDeleteMessageData):
|
||||
let apiMessage = channelAdminLogEventActionDeleteMessageData.message
|
||||
if let messageId = apiMessage.id(namespace: Namespaces.Message.Cloud), messageId == replyAttribute.messageId, let message = StoreMessage(apiMessage: apiMessage, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let replyMessage = locallyRenderedMessage(message: message, peers: peers, associatedThreadInfo: associatedThreadInfo) {
|
||||
associatedMessages[replyMessage.id] = replyMessage
|
||||
foundDeletedReplyMessage = true
|
||||
@@ -215,163 +218,191 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
|
||||
for event in apiEvents {
|
||||
switch event {
|
||||
case let .channelAdminLogEvent(id, date, userId, apiAction):
|
||||
case let .channelAdminLogEvent(channelAdminLogEventData):
|
||||
let (id, date, userId, apiAction) = (channelAdminLogEventData.id, channelAdminLogEventData.date, channelAdminLogEventData.userId, channelAdminLogEventData.action)
|
||||
var action: AdminLogEventAction?
|
||||
switch apiAction {
|
||||
case let .channelAdminLogEventActionChangeTitle(prev, new):
|
||||
case let .channelAdminLogEventActionChangeTitle(channelAdminLogEventActionChangeTitleData):
|
||||
let (prev, new) = (channelAdminLogEventActionChangeTitleData.prevValue, channelAdminLogEventActionChangeTitleData.newValue)
|
||||
action = .changeTitle(prev: prev, new: new)
|
||||
case let .channelAdminLogEventActionChangeAbout(prev, new):
|
||||
case let .channelAdminLogEventActionChangeAbout(channelAdminLogEventActionChangeAboutData):
|
||||
let (prev, new) = (channelAdminLogEventActionChangeAboutData.prevValue, channelAdminLogEventActionChangeAboutData.newValue)
|
||||
action = .changeAbout(prev: prev, new: new)
|
||||
case let .channelAdminLogEventActionChangeUsername(prev, new):
|
||||
case let .channelAdminLogEventActionChangeUsername(channelAdminLogEventActionChangeUsernameData):
|
||||
let (prev, new) = (channelAdminLogEventActionChangeUsernameData.prevValue, channelAdminLogEventActionChangeUsernameData.newValue)
|
||||
action = .changeUsername(prev: prev, new: new)
|
||||
case let .channelAdminLogEventActionChangePhoto(prev, new):
|
||||
case let .channelAdminLogEventActionChangePhoto(channelAdminLogEventActionChangePhotoData):
|
||||
let (prev, new) = (channelAdminLogEventActionChangePhotoData.prevPhoto, channelAdminLogEventActionChangePhotoData.newPhoto)
|
||||
let previousImage = telegramMediaImageFromApiPhoto(prev)
|
||||
let newImage = telegramMediaImageFromApiPhoto(new)
|
||||
action = .changePhoto(prev: (previousImage?.representations ?? [], previousImage?.videoRepresentations ?? []) , new: (newImage?.representations ?? [], newImage?.videoRepresentations ?? []))
|
||||
case let .channelAdminLogEventActionToggleInvites(new):
|
||||
action = .toggleInvites(boolFromApiValue(new))
|
||||
case let .channelAdminLogEventActionToggleSignatures(new):
|
||||
action = .toggleSignatures(boolFromApiValue(new))
|
||||
case let .channelAdminLogEventActionUpdatePinned(new):
|
||||
switch new {
|
||||
case let .channelAdminLogEventActionToggleInvites(channelAdminLogEventActionToggleInvitesData):
|
||||
action = .toggleInvites(boolFromApiValue(channelAdminLogEventActionToggleInvitesData.newValue))
|
||||
case let .channelAdminLogEventActionToggleSignatures(channelAdminLogEventActionToggleSignaturesData):
|
||||
action = .toggleSignatures(boolFromApiValue(channelAdminLogEventActionToggleSignaturesData.newValue))
|
||||
case let .channelAdminLogEventActionUpdatePinned(channelAdminLogEventActionUpdatePinnedData):
|
||||
switch channelAdminLogEventActionUpdatePinnedData.message {
|
||||
case .messageEmpty:
|
||||
action = .updatePinned(nil)
|
||||
default:
|
||||
if let message = StoreMessage(apiMessage: new, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
if let message = StoreMessage(apiMessage: channelAdminLogEventActionUpdatePinnedData.message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
action = .updatePinned(rendered)
|
||||
}
|
||||
}
|
||||
case let .channelAdminLogEventActionEditMessage(prev, new):
|
||||
case let .channelAdminLogEventActionEditMessage(channelAdminLogEventActionEditMessageData):
|
||||
let (prev, new) = (channelAdminLogEventActionEditMessageData.prevMessage, channelAdminLogEventActionEditMessageData.newMessage)
|
||||
if let prev = StoreMessage(apiMessage: prev, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let prevRendered = renderedMessage(message: prev), let new = StoreMessage(apiMessage: new, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let newRendered = renderedMessage(message: new) {
|
||||
action = .editMessage(prev: prevRendered, new: newRendered)
|
||||
}
|
||||
case let .channelAdminLogEventActionDeleteMessage(message):
|
||||
if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
case let .channelAdminLogEventActionDeleteMessage(channelAdminLogEventActionDeleteMessageData):
|
||||
if let message = StoreMessage(apiMessage: channelAdminLogEventActionDeleteMessageData.message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
action = .deleteMessage(rendered)
|
||||
}
|
||||
case .channelAdminLogEventActionParticipantJoin:
|
||||
action = .participantJoin
|
||||
case .channelAdminLogEventActionParticipantLeave:
|
||||
action = .participantLeave
|
||||
case let .channelAdminLogEventActionParticipantInvite(participant):
|
||||
let participant = ChannelParticipant(apiParticipant: participant)
|
||||
case let .channelAdminLogEventActionParticipantInvite(channelAdminLogEventActionParticipantInviteData):
|
||||
let participant = ChannelParticipant(apiParticipant: channelAdminLogEventActionParticipantInviteData.participant)
|
||||
|
||||
if let peer = peers[participant.peerId] {
|
||||
action = .participantInvite(RenderedChannelParticipant(participant: participant, peer: peer))
|
||||
}
|
||||
case let .channelAdminLogEventActionParticipantToggleBan(prev, new):
|
||||
case let .channelAdminLogEventActionParticipantToggleBan(channelAdminLogEventActionParticipantToggleBanData):
|
||||
let (prev, new) = (channelAdminLogEventActionParticipantToggleBanData.prevParticipant, channelAdminLogEventActionParticipantToggleBanData.newParticipant)
|
||||
let prevParticipant = ChannelParticipant(apiParticipant: prev)
|
||||
let newParticipant = ChannelParticipant(apiParticipant: new)
|
||||
|
||||
if let prevPeer = peers[prevParticipant.peerId], let newPeer = peers[newParticipant.peerId] {
|
||||
action = .participantToggleBan(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer))
|
||||
}
|
||||
case let .channelAdminLogEventActionParticipantToggleAdmin(prev, new):
|
||||
case let .channelAdminLogEventActionParticipantToggleAdmin(channelAdminLogEventActionParticipantToggleAdminData):
|
||||
let (prev, new) = (channelAdminLogEventActionParticipantToggleAdminData.prevParticipant, channelAdminLogEventActionParticipantToggleAdminData.newParticipant)
|
||||
let prevParticipant = ChannelParticipant(apiParticipant: prev)
|
||||
let newParticipant = ChannelParticipant(apiParticipant: new)
|
||||
|
||||
if let prevPeer = peers[prevParticipant.peerId], let newPeer = peers[newParticipant.peerId] {
|
||||
action = .participantToggleAdmin(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer))
|
||||
}
|
||||
case let .channelAdminLogEventActionChangeStickerSet(prevStickerset, newStickerset):
|
||||
case let .channelAdminLogEventActionChangeStickerSet(channelAdminLogEventActionChangeStickerSetData):
|
||||
let (prevStickerset, newStickerset) = (channelAdminLogEventActionChangeStickerSetData.prevStickerset, channelAdminLogEventActionChangeStickerSetData.newStickerset)
|
||||
action = .changeStickerPack(prev: StickerPackReference(apiInputSet: prevStickerset), new: StickerPackReference(apiInputSet: newStickerset))
|
||||
case let .channelAdminLogEventActionTogglePreHistoryHidden(value):
|
||||
action = .togglePreHistoryHidden(value == .boolTrue)
|
||||
case let .channelAdminLogEventActionDefaultBannedRights(prevBannedRights, newBannedRights):
|
||||
case let .channelAdminLogEventActionTogglePreHistoryHidden(channelAdminLogEventActionTogglePreHistoryHiddenData):
|
||||
action = .togglePreHistoryHidden(channelAdminLogEventActionTogglePreHistoryHiddenData.newValue == .boolTrue)
|
||||
case let .channelAdminLogEventActionDefaultBannedRights(channelAdminLogEventActionDefaultBannedRightsData):
|
||||
let (prevBannedRights, newBannedRights) = (channelAdminLogEventActionDefaultBannedRightsData.prevBannedRights, channelAdminLogEventActionDefaultBannedRightsData.newBannedRights)
|
||||
action = .updateDefaultBannedRights(prev: TelegramChatBannedRights(apiBannedRights: prevBannedRights), new: TelegramChatBannedRights(apiBannedRights: newBannedRights))
|
||||
case let .channelAdminLogEventActionStopPoll(message):
|
||||
if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
case let .channelAdminLogEventActionStopPoll(channelAdminLogEventActionStopPollData):
|
||||
if let message = StoreMessage(apiMessage: channelAdminLogEventActionStopPollData.message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
action = .pollStopped(rendered)
|
||||
}
|
||||
case let .channelAdminLogEventActionChangeLinkedChat(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeLinkedChat(channelAdminLogEventActionChangeLinkedChatData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeLinkedChatData.prevValue, channelAdminLogEventActionChangeLinkedChatData.newValue)
|
||||
action = .linkedPeerUpdated(previous: prevValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(prevValue))], updated: newValue == 0 ? nil : peers[PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(newValue))])
|
||||
case let .channelAdminLogEventActionChangeLocation(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeLocation(channelAdminLogEventActionChangeLocationData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeLocationData.prevValue, channelAdminLogEventActionChangeLocationData.newValue)
|
||||
action = .changeGeoLocation(previous: PeerGeoLocation(apiLocation: prevValue), updated: PeerGeoLocation(apiLocation: newValue))
|
||||
case let .channelAdminLogEventActionToggleSlowMode(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionToggleSlowMode(channelAdminLogEventActionToggleSlowModeData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionToggleSlowModeData.prevValue, channelAdminLogEventActionToggleSlowModeData.newValue)
|
||||
action = .updateSlowmode(previous: prevValue == 0 ? nil : prevValue, updated: newValue == 0 ? nil : newValue)
|
||||
case .channelAdminLogEventActionStartGroupCall:
|
||||
action = .startGroupCall
|
||||
case .channelAdminLogEventActionDiscardGroupCall:
|
||||
action = .endGroupCall
|
||||
case let .channelAdminLogEventActionParticipantMute(participant):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(participant)
|
||||
case let .channelAdminLogEventActionParticipantMute(channelAdminLogEventActionParticipantMuteData):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(channelAdminLogEventActionParticipantMuteData.participant)
|
||||
action = .groupCallUpdateParticipantMuteStatus(peerId: parsedParticipant.peerId, isMuted: true)
|
||||
case let .channelAdminLogEventActionParticipantUnmute(participant):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(participant)
|
||||
case let .channelAdminLogEventActionParticipantUnmute(channelAdminLogEventActionParticipantUnmuteData):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(channelAdminLogEventActionParticipantUnmuteData.participant)
|
||||
action = .groupCallUpdateParticipantMuteStatus(peerId: parsedParticipant.peerId, isMuted: false)
|
||||
case let .channelAdminLogEventActionToggleGroupCallSetting(joinMuted):
|
||||
action = .updateGroupCallSettings(joinMuted: joinMuted == .boolTrue)
|
||||
case let .channelAdminLogEventActionExportedInviteDelete(invite):
|
||||
action = .deleteExportedInvitation(ExportedInvitation(apiExportedInvite: invite))
|
||||
case let .channelAdminLogEventActionExportedInviteRevoke(invite):
|
||||
action = .revokeExportedInvitation(ExportedInvitation(apiExportedInvite: invite))
|
||||
case let .channelAdminLogEventActionExportedInviteEdit(prevInvite, newInvite):
|
||||
case let .channelAdminLogEventActionToggleGroupCallSetting(channelAdminLogEventActionToggleGroupCallSettingData):
|
||||
action = .updateGroupCallSettings(joinMuted: channelAdminLogEventActionToggleGroupCallSettingData.joinMuted == .boolTrue)
|
||||
case let .channelAdminLogEventActionExportedInviteDelete(channelAdminLogEventActionExportedInviteDeleteData):
|
||||
action = .deleteExportedInvitation(ExportedInvitation(apiExportedInvite: channelAdminLogEventActionExportedInviteDeleteData.invite))
|
||||
case let .channelAdminLogEventActionExportedInviteRevoke(channelAdminLogEventActionExportedInviteRevokeData):
|
||||
action = .revokeExportedInvitation(ExportedInvitation(apiExportedInvite: channelAdminLogEventActionExportedInviteRevokeData.invite))
|
||||
case let .channelAdminLogEventActionExportedInviteEdit(channelAdminLogEventActionExportedInviteEditData):
|
||||
let (prevInvite, newInvite) = (channelAdminLogEventActionExportedInviteEditData.prevInvite, channelAdminLogEventActionExportedInviteEditData.newInvite)
|
||||
action = .editExportedInvitation(previous: ExportedInvitation(apiExportedInvite: prevInvite), updated: ExportedInvitation(apiExportedInvite: newInvite))
|
||||
case let .channelAdminLogEventActionParticipantJoinByInvite(flags, invite):
|
||||
case let .channelAdminLogEventActionParticipantJoinByInvite(channelAdminLogEventActionParticipantJoinByInviteData):
|
||||
let (flags, invite) = (channelAdminLogEventActionParticipantJoinByInviteData.flags, channelAdminLogEventActionParticipantJoinByInviteData.invite)
|
||||
action = .participantJoinedViaInvite(invitation: ExportedInvitation(apiExportedInvite: invite), joinedViaFolderLink: (flags & (1 << 0)) != 0)
|
||||
case let .channelAdminLogEventActionParticipantVolume(participant):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(participant)
|
||||
case let .channelAdminLogEventActionParticipantVolume(channelAdminLogEventActionParticipantVolumeData):
|
||||
let parsedParticipant = GroupCallParticipantsContext.Update.StateUpdate.ParticipantUpdate(channelAdminLogEventActionParticipantVolumeData.participant)
|
||||
action = .groupCallUpdateParticipantVolume(peerId: parsedParticipant.peerId, volume: parsedParticipant.volume ?? 10000)
|
||||
case let .channelAdminLogEventActionChangeHistoryTTL(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeHistoryTTL(channelAdminLogEventActionChangeHistoryTTLData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeHistoryTTLData.prevValue, channelAdminLogEventActionChangeHistoryTTLData.newValue)
|
||||
action = .changeHistoryTTL(previousValue: prevValue, updatedValue: newValue)
|
||||
case let .channelAdminLogEventActionParticipantJoinByRequest(invite, approvedBy):
|
||||
case let .channelAdminLogEventActionParticipantJoinByRequest(channelAdminLogEventActionParticipantJoinByRequestData):
|
||||
let (invite, approvedBy) = (channelAdminLogEventActionParticipantJoinByRequestData.invite, channelAdminLogEventActionParticipantJoinByRequestData.approvedBy)
|
||||
action = .participantJoinByRequest(invitation: ExportedInvitation(apiExportedInvite: invite), approvedBy: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(approvedBy)))
|
||||
case let .channelAdminLogEventActionToggleNoForwards(new):
|
||||
action = .toggleCopyProtection(boolFromApiValue(new))
|
||||
case let .channelAdminLogEventActionSendMessage(message):
|
||||
if let message = StoreMessage(apiMessage: message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
case let .channelAdminLogEventActionToggleNoForwards(channelAdminLogEventActionToggleNoForwardsData):
|
||||
action = .toggleCopyProtection(boolFromApiValue(channelAdminLogEventActionToggleNoForwardsData.newValue))
|
||||
case let .channelAdminLogEventActionSendMessage(channelAdminLogEventActionSendMessageData):
|
||||
if let message = StoreMessage(apiMessage: channelAdminLogEventActionSendMessageData.message, accountPeerId: accountPeerId, peerIsForum: peer.isForum), let rendered = renderedMessage(message: message) {
|
||||
action = .sendMessage(rendered)
|
||||
}
|
||||
case let .channelAdminLogEventActionChangeAvailableReactions(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeAvailableReactions(channelAdminLogEventActionChangeAvailableReactionsData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeAvailableReactionsData.prevValue, channelAdminLogEventActionChangeAvailableReactionsData.newValue)
|
||||
action = .changeAvailableReactions(previousValue: PeerAllowedReactions(apiReactions: prevValue), updatedValue: PeerAllowedReactions(apiReactions: newValue))
|
||||
case let .channelAdminLogEventActionChangeUsernames(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeUsernames(channelAdminLogEventActionChangeUsernamesData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeUsernamesData.prevValue, channelAdminLogEventActionChangeUsernamesData.newValue)
|
||||
action = .changeUsernames(prev: prevValue, new: newValue)
|
||||
case let .channelAdminLogEventActionCreateTopic(topic):
|
||||
switch topic {
|
||||
case let .forumTopic(_, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .channelAdminLogEventActionCreateTopic(channelAdminLogEventActionCreateTopicData):
|
||||
switch channelAdminLogEventActionCreateTopicData.topic {
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (title, iconColor, iconEmojiId) = (forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
action = .createTopic(info: EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor))
|
||||
case .forumTopicDeleted:
|
||||
action = .createTopic(info: EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0))
|
||||
}
|
||||
case let .channelAdminLogEventActionDeleteTopic(topic):
|
||||
case let .channelAdminLogEventActionDeleteTopic(channelAdminLogEventActionDeleteTopicData):
|
||||
let topic = channelAdminLogEventActionDeleteTopicData.topic
|
||||
switch topic {
|
||||
case let .forumTopic(_, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (title, iconColor, iconEmojiId) = (forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
action = .deleteTopic(info: EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor))
|
||||
case .forumTopicDeleted:
|
||||
action = .deleteTopic(info: EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0))
|
||||
}
|
||||
case let .channelAdminLogEventActionEditTopic(prevTopic, newTopic):
|
||||
case let .channelAdminLogEventActionEditTopic(channelAdminLogEventActionEditTopicData):
|
||||
let (prevTopic, newTopic) = (channelAdminLogEventActionEditTopicData.prevTopic, channelAdminLogEventActionEditTopicData.newTopic)
|
||||
let prevInfo: AdminLogEventAction.ForumTopicInfo
|
||||
switch prevTopic {
|
||||
case let .forumTopic(flags, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (flags, title, iconColor, iconEmojiId) = (forumTopicData.flags, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
prevInfo = AdminLogEventAction.ForumTopicInfo(info: EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor), isClosed: (flags & (1 << 2)) != 0, isHidden: (flags & (1 << 6)) != 0)
|
||||
case .forumTopicDeleted:
|
||||
prevInfo = AdminLogEventAction.ForumTopicInfo(info: EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0), isClosed: false, isHidden: false)
|
||||
}
|
||||
|
||||
|
||||
let newInfo: AdminLogEventAction.ForumTopicInfo
|
||||
switch newTopic {
|
||||
case let .forumTopic(flags, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (flags, title, iconColor, iconEmojiId) = (forumTopicData.flags, forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
newInfo = AdminLogEventAction.ForumTopicInfo(info: EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor), isClosed: (flags & (1 << 2)) != 0, isHidden: (flags & (1 << 6)) != 0)
|
||||
case .forumTopicDeleted:
|
||||
newInfo = AdminLogEventAction.ForumTopicInfo(info: EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0), isClosed: false, isHidden: false)
|
||||
}
|
||||
|
||||
action = .editTopic(prevInfo: prevInfo, newInfo: newInfo)
|
||||
case let .channelAdminLogEventActionPinTopic(_, prevTopic, newTopic):
|
||||
case let .channelAdminLogEventActionPinTopic(channelAdminLogEventActionPinTopicData):
|
||||
let (prevTopic, newTopic) = (channelAdminLogEventActionPinTopicData.prevTopic, channelAdminLogEventActionPinTopicData.newTopic)
|
||||
let prevInfo: EngineMessageHistoryThread.Info?
|
||||
switch prevTopic {
|
||||
case let .forumTopic(_, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (title, iconColor, iconEmojiId) = (forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
prevInfo = EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor)
|
||||
case .forumTopicDeleted:
|
||||
prevInfo = EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0)
|
||||
case .none:
|
||||
prevInfo = nil
|
||||
}
|
||||
|
||||
|
||||
let newInfo: EngineMessageHistoryThread.Info?
|
||||
switch newTopic {
|
||||
case let .forumTopic(_, _, _, _, title, iconColor, iconEmojiId, _, _, _, _, _, _, _, _, _):
|
||||
case let .forumTopic(forumTopicData):
|
||||
let (title, iconColor, iconEmojiId) = (forumTopicData.title, forumTopicData.iconColor, forumTopicData.iconEmojiId)
|
||||
newInfo = EngineMessageHistoryThread.Info(title: title, icon: iconEmojiId, iconColor: iconColor)
|
||||
case .forumTopicDeleted:
|
||||
newInfo = EngineMessageHistoryThread.Info(title: "", icon: nil, iconColor: 0)
|
||||
@@ -379,32 +410,39 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
newInfo = nil
|
||||
}
|
||||
action = .pinTopic(prevInfo: prevInfo, newInfo: newInfo)
|
||||
case let .channelAdminLogEventActionToggleForum(newValue):
|
||||
action = .toggleForum(isForum: newValue == .boolTrue)
|
||||
case let .channelAdminLogEventActionToggleAntiSpam(newValue):
|
||||
action = .toggleAntiSpam(isEnabled: newValue == .boolTrue)
|
||||
case let .channelAdminLogEventActionChangePeerColor(prevValue, newValue):
|
||||
guard case let .peerColor(_, prevColor, prevBackgroundEmojiIdValue) = prevValue, case let .peerColor(_, newColor, newBackgroundEmojiIdValue) = newValue else {
|
||||
case let .channelAdminLogEventActionToggleForum(channelAdminLogEventActionToggleForumData):
|
||||
action = .toggleForum(isForum: channelAdminLogEventActionToggleForumData.newValue == .boolTrue)
|
||||
case let .channelAdminLogEventActionToggleAntiSpam(channelAdminLogEventActionToggleAntiSpamData):
|
||||
action = .toggleAntiSpam(isEnabled: channelAdminLogEventActionToggleAntiSpamData.newValue == .boolTrue)
|
||||
case let .channelAdminLogEventActionChangePeerColor(channelAdminLogEventActionChangePeerColorData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangePeerColorData.prevValue, channelAdminLogEventActionChangePeerColorData.newValue)
|
||||
guard case let .peerColor(prevPeerColorData) = prevValue, case let .peerColor(newPeerColorData) = newValue else {
|
||||
continue
|
||||
}
|
||||
let (prevColor, prevBackgroundEmojiId) = (prevPeerColorData.color, prevPeerColorData.backgroundEmojiId)
|
||||
let (newColor, newBackgroundEmojiId) = (newPeerColorData.color, newPeerColorData.backgroundEmojiId)
|
||||
let prevColorIndex = prevColor ?? 0
|
||||
let prevEmojiId = prevBackgroundEmojiIdValue
|
||||
|
||||
let prevEmojiId = prevBackgroundEmojiId
|
||||
|
||||
let newColorIndex = newColor ?? 0
|
||||
let newEmojiId = newBackgroundEmojiIdValue
|
||||
|
||||
let newEmojiId = newBackgroundEmojiId
|
||||
|
||||
action = .changeNameColor(prevColor: PeerNameColor(rawValue: prevColorIndex), prevIcon: prevEmojiId, newColor: PeerNameColor(rawValue: newColorIndex), newIcon: newEmojiId)
|
||||
case let .channelAdminLogEventActionChangeProfilePeerColor(prevValue, newValue):
|
||||
guard case let .peerColor(_, prevColorIndex, prevEmojiId) = prevValue, case let .peerColor(_, newColorIndex, newEmojiId) = newValue else {
|
||||
case let .channelAdminLogEventActionChangeProfilePeerColor(channelAdminLogEventActionChangeProfilePeerColorData):
|
||||
guard case let .peerColor(prevPeerColorData) = channelAdminLogEventActionChangeProfilePeerColorData.prevValue, case let .peerColor(newPeerColorData) = channelAdminLogEventActionChangeProfilePeerColorData.newValue else {
|
||||
continue
|
||||
}
|
||||
action = .changeProfileColor(prevColor: prevColorIndex.flatMap(PeerNameColor.init(rawValue:)), prevIcon: prevEmojiId, newColor: newColorIndex.flatMap(PeerNameColor.init(rawValue:)), newIcon: newEmojiId)
|
||||
case let .channelAdminLogEventActionChangeWallpaper(prevValue, newValue):
|
||||
let (prevColor, prevBackgroundEmojiId) = (prevPeerColorData.color, prevPeerColorData.backgroundEmojiId)
|
||||
let (newColor, newBackgroundEmojiId) = (newPeerColorData.color, newPeerColorData.backgroundEmojiId)
|
||||
action = .changeProfileColor(prevColor: prevColor.flatMap(PeerNameColor.init(rawValue:)), prevIcon: prevBackgroundEmojiId, newColor: newColor.flatMap(PeerNameColor.init(rawValue:)), newIcon: newBackgroundEmojiId)
|
||||
case let .channelAdminLogEventActionChangeWallpaper(channelAdminLogEventActionChangeWallpaperData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeWallpaperData.prevValue, channelAdminLogEventActionChangeWallpaperData.newValue)
|
||||
let prev: TelegramWallpaper?
|
||||
if case let .wallPaperNoFile(_, _, settings) = prevValue {
|
||||
if case let .wallPaperNoFile(wallPaperNoFileData) = prevValue {
|
||||
let (_, _, settings) = (wallPaperNoFileData.id, wallPaperNoFileData.flags, wallPaperNoFileData.settings)
|
||||
if settings == nil {
|
||||
prev = nil
|
||||
} else if case let .wallPaperSettings(flags, _, _, _, _, _, _, _) = settings, flags == 0 {
|
||||
} else if case let .wallPaperSettings(wallPaperSettingsData) = settings, wallPaperSettingsData.flags == 0 {
|
||||
prev = nil
|
||||
} else {
|
||||
prev = TelegramWallpaper(apiWallpaper: prevValue)
|
||||
@@ -413,10 +451,11 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
prev = TelegramWallpaper(apiWallpaper: prevValue)
|
||||
}
|
||||
let new: TelegramWallpaper?
|
||||
if case let .wallPaperNoFile(_, _, settings) = newValue {
|
||||
if case let .wallPaperNoFile(wallPaperNoFileData) = newValue {
|
||||
let (_, _, settings) = (wallPaperNoFileData.id, wallPaperNoFileData.flags, wallPaperNoFileData.settings)
|
||||
if settings == nil {
|
||||
new = nil
|
||||
} else if case let .wallPaperSettings(flags, _, _, _, _, _, _, _) = settings, flags == 0 {
|
||||
} else if case let .wallPaperSettings(wallPaperSettingsData) = settings, wallPaperSettingsData.flags == 0 {
|
||||
new = nil
|
||||
} else {
|
||||
new = TelegramWallpaper(apiWallpaper: newValue)
|
||||
@@ -425,20 +464,24 @@ func channelAdminLogEvents(accountPeerId: PeerId, postbox: Postbox, network: Net
|
||||
new = TelegramWallpaper(apiWallpaper: newValue)
|
||||
}
|
||||
action = .changeWallpaper(prev: prev, new: new)
|
||||
case let .channelAdminLogEventActionChangeEmojiStatus(prevValue, newValue):
|
||||
case let .channelAdminLogEventActionChangeEmojiStatus(channelAdminLogEventActionChangeEmojiStatusData):
|
||||
let (prevValue, newValue) = (channelAdminLogEventActionChangeEmojiStatusData.prevValue, channelAdminLogEventActionChangeEmojiStatusData.newValue)
|
||||
action = .changeStatus(prev: PeerEmojiStatus(apiStatus: prevValue), new: PeerEmojiStatus(apiStatus: newValue))
|
||||
case let .channelAdminLogEventActionChangeEmojiStickerSet(prevStickerset, newStickerset):
|
||||
case let .channelAdminLogEventActionChangeEmojiStickerSet(channelAdminLogEventActionChangeEmojiStickerSetData):
|
||||
let (prevStickerset, newStickerset) = (channelAdminLogEventActionChangeEmojiStickerSetData.prevStickerset, channelAdminLogEventActionChangeEmojiStickerSetData.newStickerset)
|
||||
action = .changeEmojiPack(prev: StickerPackReference(apiInputSet: prevStickerset), new: StickerPackReference(apiInputSet: newStickerset))
|
||||
case let .channelAdminLogEventActionToggleSignatureProfiles(newValue):
|
||||
action = .toggleSignatureProfiles(boolFromApiValue(newValue))
|
||||
case let .channelAdminLogEventActionParticipantSubExtend(prev, new):
|
||||
case let .channelAdminLogEventActionToggleSignatureProfiles(channelAdminLogEventActionToggleSignatureProfilesData):
|
||||
action = .toggleSignatureProfiles(boolFromApiValue(channelAdminLogEventActionToggleSignatureProfilesData.newValue))
|
||||
case let .channelAdminLogEventActionParticipantSubExtend(channelAdminLogEventActionParticipantSubExtendData):
|
||||
let (prev, new) = (channelAdminLogEventActionParticipantSubExtendData.prevParticipant, channelAdminLogEventActionParticipantSubExtendData.newParticipant)
|
||||
let prevParticipant = ChannelParticipant(apiParticipant: prev)
|
||||
let newParticipant = ChannelParticipant(apiParticipant: new)
|
||||
|
||||
if let prevPeer = peers[prevParticipant.peerId], let newPeer = peers[newParticipant.peerId] {
|
||||
action = .participantSubscriptionExtended(prev: RenderedChannelParticipant(participant: prevParticipant, peer: prevPeer), new: RenderedChannelParticipant(participant: newParticipant, peer: newPeer))
|
||||
}
|
||||
case let .channelAdminLogEventActionToggleAutotranslation(newValue):
|
||||
case let .channelAdminLogEventActionToggleAutotranslation(channelAdminLogEventActionToggleAutotranslationData):
|
||||
let newValue = channelAdminLogEventActionToggleAutotranslationData.newValue
|
||||
action = .toggleAutoTranslation(boolFromApiValue(newValue))
|
||||
}
|
||||
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
|
||||
@@ -32,7 +32,7 @@ func _internal_updateChannelMemberBannedRights(account: Account, peerId: PeerId,
|
||||
if let rights = rights, !rights.flags.isEmpty {
|
||||
apiRights = rights.apiBannedRights
|
||||
} else {
|
||||
apiRights = .chatBannedRights(flags: 0, untilDate: 0)
|
||||
apiRights = .chatBannedRights(.init(flags: 0, untilDate: 0))
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.channels.editBanned(channel: inputChannel, participant: inputPeer, bannedRights: apiRights))
|
||||
|
||||
@@ -37,7 +37,7 @@ private func createChannel(postbox: Postbox, network: Network, stateManager: Acc
|
||||
var address: String?
|
||||
if let location = location {
|
||||
flags |= (1 << 2)
|
||||
geoPoint = .inputGeoPoint(flags: 0, lat: location.latitude, long: location.longitude, accuracyRadius: nil)
|
||||
geoPoint = .inputGeoPoint(.init(flags: 0, lat: location.latitude, long: location.longitude, accuracyRadius: nil))
|
||||
address = location.address
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ func _internal_channelMembers(postbox: Postbox, network: Network, accountPeerId:
|
||||
case .all:
|
||||
apiFilter = .channelParticipantsRecent
|
||||
case let .search(query):
|
||||
apiFilter = .channelParticipantsSearch(q: query)
|
||||
apiFilter = .channelParticipantsSearch(Api.ChannelParticipantsFilter.Cons_channelParticipantsSearch(q: query))
|
||||
}
|
||||
case let .mentions(threadId, filter):
|
||||
switch filter {
|
||||
@@ -49,7 +49,7 @@ func _internal_channelMembers(postbox: Postbox, network: Network, accountPeerId:
|
||||
if threadId != nil {
|
||||
flags |= 1 << 1
|
||||
}
|
||||
apiFilter = .channelParticipantsMentions(flags: flags, q: nil, topMsgId: threadId?.id)
|
||||
apiFilter = .channelParticipantsMentions(Api.ChannelParticipantsFilter.Cons_channelParticipantsMentions(flags: flags, q: nil, topMsgId: threadId?.id))
|
||||
case let .search(query):
|
||||
var flags: Int32 = 0
|
||||
if threadId != nil {
|
||||
@@ -58,32 +58,32 @@ func _internal_channelMembers(postbox: Postbox, network: Network, accountPeerId:
|
||||
if !query.isEmpty {
|
||||
flags |= 1 << 0
|
||||
}
|
||||
apiFilter = .channelParticipantsMentions(flags: flags, q: query.isEmpty ? nil : query, topMsgId: threadId?.id)
|
||||
apiFilter = .channelParticipantsMentions(Api.ChannelParticipantsFilter.Cons_channelParticipantsMentions(flags: flags, q: query.isEmpty ? nil : query, topMsgId: threadId?.id))
|
||||
}
|
||||
case .admins:
|
||||
apiFilter = .channelParticipantsAdmins
|
||||
case let .contacts(filter):
|
||||
switch filter {
|
||||
case .all:
|
||||
apiFilter = .channelParticipantsContacts(q: "")
|
||||
apiFilter = .channelParticipantsContacts(Api.ChannelParticipantsFilter.Cons_channelParticipantsContacts(q: ""))
|
||||
case let .search(query):
|
||||
apiFilter = .channelParticipantsContacts(q: query)
|
||||
apiFilter = .channelParticipantsContacts(Api.ChannelParticipantsFilter.Cons_channelParticipantsContacts(q: query))
|
||||
}
|
||||
case .bots:
|
||||
apiFilter = .channelParticipantsBots
|
||||
case let .restricted(filter):
|
||||
switch filter {
|
||||
case .all:
|
||||
apiFilter = .channelParticipantsBanned(q: "")
|
||||
apiFilter = .channelParticipantsBanned(Api.ChannelParticipantsFilter.Cons_channelParticipantsBanned(q: ""))
|
||||
case let .search(query):
|
||||
apiFilter = .channelParticipantsBanned(q: query)
|
||||
apiFilter = .channelParticipantsBanned(Api.ChannelParticipantsFilter.Cons_channelParticipantsBanned(q: query))
|
||||
}
|
||||
case let .banned(filter):
|
||||
switch filter {
|
||||
case .all:
|
||||
apiFilter = .channelParticipantsKicked(q: "")
|
||||
apiFilter = .channelParticipantsKicked(Api.ChannelParticipantsFilter.Cons_channelParticipantsKicked(q: ""))
|
||||
case let .search(query):
|
||||
apiFilter = .channelParticipantsKicked(q: query)
|
||||
apiFilter = .channelParticipantsKicked(Api.ChannelParticipantsFilter.Cons_channelParticipantsKicked(q: query))
|
||||
}
|
||||
}
|
||||
return network.request(Api.functions.channels.getParticipants(channel: inputChannel, filter: apiFilter, offset: offset, limit: limit, hash: hash))
|
||||
@@ -95,7 +95,8 @@ func _internal_channelMembers(postbox: Postbox, network: Network, accountPeerId:
|
||||
return postbox.transaction { transaction -> [RenderedChannelParticipant]? in
|
||||
var items: [RenderedChannelParticipant] = []
|
||||
switch result {
|
||||
case let .channelParticipants(_, participants, chats, users):
|
||||
case let .channelParticipants(channelParticipantsData):
|
||||
let (participants, chats, users) = (channelParticipantsData.participants, channelParticipantsData.chats, channelParticipantsData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
var peers: [PeerId: Peer] = [:]
|
||||
|
||||
@@ -101,7 +101,7 @@ func _internal_updateChannelOwnership(account: Account, channelId: PeerId, membe
|
||||
guard let kdfResult = passwordKDF(encryptionProvider: account.network.encryptionProvider, password: password, derivation: currentPasswordDerivation, srpSessionData: srpSessionData) else {
|
||||
return .fail(.generic)
|
||||
}
|
||||
return .single(.inputCheckPasswordSRP(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1)))
|
||||
return .single(.inputCheckPasswordSRP(.init(srpId: kdfResult.id, A: Buffer(data: kdfResult.A), M1: Buffer(data: kdfResult.M1))))
|
||||
} else {
|
||||
return .fail(.twoStepAuthMissing)
|
||||
}
|
||||
|
||||
@@ -104,10 +104,12 @@ func _internal_requestRecommendedChannels(account: Account, peerId: EnginePeer.I
|
||||
let parsedPeers: AccumulatedPeers
|
||||
var count: Int32
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
count = Int32(apiChats.count)
|
||||
case let .chatsSlice(apiCount, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let (apiCount, apiChats) = (chatsSliceData.count, chatsSliceData.chats)
|
||||
chats = apiChats
|
||||
count = apiCount
|
||||
}
|
||||
@@ -117,7 +119,7 @@ func _internal_requestRecommendedChannels(account: Account, peerId: EnginePeer.I
|
||||
for chat in chats {
|
||||
if let peer = transaction.getPeer(chat.peerId) {
|
||||
peers.append(EnginePeer(peer))
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat, let participantsCount = participantsCount {
|
||||
if case let .channel(channelData) = chat, let participantsCount = channelData.participantsCount {
|
||||
transaction.updatePeerCachedData(peerIds: Set([peer.id]), update: { _, current in
|
||||
var current = current as? CachedChannelData ?? CachedChannelData()
|
||||
var participantsSummary = current.participantsSummary
|
||||
@@ -167,7 +169,8 @@ func _internal_requestRecommendedApps(account: Account, forceUpdate: Bool) -> Si
|
||||
let users: [Api.User]
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case let .popularAppBots(_, nextOffset, apiUsers):
|
||||
case let .popularAppBots(popularAppBotsData):
|
||||
let (nextOffset, apiUsers) = (popularAppBotsData.nextOffset, popularAppBotsData.users)
|
||||
let _ = nextOffset
|
||||
users = apiUsers
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import SGSimpleSettings
|
||||
import Foundation
|
||||
import Postbox
|
||||
import SwiftSignalKit
|
||||
@@ -341,11 +342,13 @@ extension ChatListFilter {
|
||||
switch apiFilter {
|
||||
case .dialogFilterDefault:
|
||||
self = .allChats
|
||||
case let .dialogFilter(flags, id, title, emoticon, color, pinnedPeers, includePeers, excludePeers):
|
||||
case let .dialogFilter(dialogFilterData):
|
||||
let (flags, id, title, emoticon, color, pinnedPeers, includePeers, excludePeers) = (dialogFilterData.flags, dialogFilterData.id, dialogFilterData.title, dialogFilterData.emoticon, dialogFilterData.color, dialogFilterData.pinnedPeers, dialogFilterData.includePeers, dialogFilterData.excludePeers)
|
||||
let titleText: String
|
||||
let titleEntities: [MessageTextEntity]
|
||||
switch title {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
titleText = text
|
||||
titleEntities = messageTextEntitiesFromApiEntities(entities)
|
||||
}
|
||||
@@ -363,22 +366,28 @@ extension ChatListFilter {
|
||||
excludeArchived: (flags & (1 << 13)) != 0,
|
||||
includePeers: ChatListFilterIncludePeers(rawPeers: includePeers.compactMap { peer -> PeerId? in
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}, rawPinnedPeers: pinnedPeers.compactMap { peer -> PeerId? in
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
return nil
|
||||
@@ -386,11 +395,14 @@ extension ChatListFilter {
|
||||
}),
|
||||
excludePeers: excludePeers.compactMap { peer -> PeerId? in
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
return nil
|
||||
@@ -399,16 +411,18 @@ extension ChatListFilter {
|
||||
color: color.flatMap(PeerNameColor.init(rawValue:))
|
||||
)
|
||||
)
|
||||
case let .dialogFilterChatlist(flags, id, title, emoticon, color, pinnedPeers, includePeers):
|
||||
case let .dialogFilterChatlist(dialogFilterChatlistData):
|
||||
let (flags, id, title, emoticon, color, pinnedPeers, includePeers) = (dialogFilterChatlistData.flags, dialogFilterChatlistData.id, dialogFilterChatlistData.title, dialogFilterChatlistData.emoticon, dialogFilterChatlistData.color, dialogFilterChatlistData.pinnedPeers, dialogFilterChatlistData.includePeers)
|
||||
let titleText: String
|
||||
let titleEntities: [MessageTextEntity]
|
||||
switch title {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
titleText = text
|
||||
titleEntities = messageTextEntitiesFromApiEntities(entities)
|
||||
}
|
||||
let disableTitleAnimations = (flags & (1 << 28)) != 0
|
||||
|
||||
|
||||
self = .filter(
|
||||
id: id,
|
||||
title: ChatFolderTitle(text: titleText, entities: titleEntities, enableAnimations: !disableTitleAnimations),
|
||||
@@ -422,22 +436,28 @@ extension ChatListFilter {
|
||||
excludeArchived: false,
|
||||
includePeers: ChatListFilterIncludePeers(rawPeers: includePeers.compactMap { peer -> PeerId? in
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}, rawPinnedPeers: pinnedPeers.compactMap { peer -> PeerId? in
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
return PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
return nil
|
||||
@@ -449,7 +469,7 @@ extension ChatListFilter {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func apiFilter(transaction: Transaction) -> Api.DialogFilter? {
|
||||
switch self {
|
||||
case .allChats:
|
||||
@@ -466,14 +486,14 @@ extension ChatListFilter {
|
||||
if !title.enableAnimations {
|
||||
flags |= 1 << 28
|
||||
}
|
||||
return .dialogFilterChatlist(flags: flags, id: id, title: .textWithEntities(text: title.text, entities: apiEntitiesFromMessageTextEntities(title.entities, associatedPeers: SimpleDictionary())), emoticon: emoticon, color: data.color?.rawValue, pinnedPeers: data.includePeers.pinnedPeers.compactMap { peerId -> Api.InputPeer? in
|
||||
return .dialogFilterChatlist(.init(flags: flags, id: id, title: .textWithEntities(.init(text: title.text, entities: apiEntitiesFromMessageTextEntities(title.entities, associatedPeers: SimpleDictionary()))), emoticon: emoticon, color: data.color?.rawValue, pinnedPeers: data.includePeers.pinnedPeers.compactMap { peerId -> Api.InputPeer? in
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
}, includePeers: data.includePeers.peers.compactMap { peerId -> Api.InputPeer? in
|
||||
if data.includePeers.pinnedPeers.contains(peerId) {
|
||||
return nil
|
||||
}
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
})
|
||||
}))
|
||||
} else {
|
||||
var flags: Int32 = 0
|
||||
if data.excludeMuted {
|
||||
@@ -495,7 +515,7 @@ extension ChatListFilter {
|
||||
if !title.enableAnimations {
|
||||
flags |= 1 << 28
|
||||
}
|
||||
return .dialogFilter(flags: flags, id: id, title: .textWithEntities(text: title.text, entities: apiEntitiesFromMessageTextEntities(title.entities, associatedPeers: SimpleDictionary())), emoticon: emoticon, color: data.color?.rawValue, pinnedPeers: data.includePeers.pinnedPeers.compactMap { peerId -> Api.InputPeer? in
|
||||
return .dialogFilter(.init(flags: flags, id: id, title: .textWithEntities(.init(text: title.text, entities: apiEntitiesFromMessageTextEntities(title.entities, associatedPeers: SimpleDictionary()))), emoticon: emoticon, color: data.color?.rawValue, pinnedPeers: data.includePeers.pinnedPeers.compactMap { peerId -> Api.InputPeer? in
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
}, includePeers: data.includePeers.peers.compactMap { peerId -> Api.InputPeer? in
|
||||
if data.includePeers.pinnedPeers.contains(peerId) {
|
||||
@@ -504,7 +524,7 @@ extension ChatListFilter {
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
}, excludePeers: data.excludePeers.compactMap { peerId -> Api.InputPeer? in
|
||||
return transaction.getPeer(peerId).flatMap(apiInputPeer)
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -560,7 +580,8 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
|> mapToSignal { result -> Signal<([ChatListFilter], Bool), RequestChatListFiltersError> in
|
||||
return postbox.transaction { transaction -> ([ChatListFilter], [Api.InputPeer], [Api.InputPeer], Bool) in
|
||||
switch result {
|
||||
case let .dialogFilters(flags, apiFilters):
|
||||
case let .dialogFilters(dialogFiltersData):
|
||||
let (flags, apiFilters) = (dialogFiltersData.flags, dialogFiltersData.filters)
|
||||
let tagsEnabled = (flags & (1 << 0)) != 0
|
||||
|
||||
var filters: [ChatListFilter] = []
|
||||
@@ -574,15 +595,19 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
switch apiFilter {
|
||||
case .dialogFilterDefault:
|
||||
break
|
||||
case let .dialogFilter(_, _, _, _, _, pinnedPeers, includePeers, excludePeers):
|
||||
case let .dialogFilter(dialogFilterData):
|
||||
let (pinnedPeers, includePeers, excludePeers) = (dialogFilterData.pinnedPeers, dialogFilterData.includePeers, dialogFilterData.excludePeers)
|
||||
for peer in pinnedPeers + includePeers + excludePeers {
|
||||
var peerId: PeerId?
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
break
|
||||
@@ -594,15 +619,18 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for peer in pinnedPeers {
|
||||
var peerId: PeerId?
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
break
|
||||
@@ -614,15 +642,19 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .dialogFilterChatlist(_, _, _, _, _, pinnedPeers, includePeers):
|
||||
case let .dialogFilterChatlist(dialogFilterChatlistData):
|
||||
let (pinnedPeers, includePeers) = (dialogFilterChatlistData.pinnedPeers, dialogFilterChatlistData.includePeers)
|
||||
for peer in pinnedPeers + includePeers {
|
||||
var peerId: PeerId?
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
break
|
||||
@@ -634,15 +666,18 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for peer in pinnedPeers {
|
||||
var peerId: PeerId?
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, _):
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let userId = inputPeerUserData.userId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .inputPeerChat(chatId):
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let chatId = inputPeerChatData.chatId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .inputPeerChannel(channelId, _):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let channelId = inputPeerChannelData.channelId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
default:
|
||||
break
|
||||
@@ -668,13 +703,16 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
var missingGroups: [Int64] = []
|
||||
for peer in missingPeers {
|
||||
switch peer {
|
||||
case let .inputPeerUser(userId, accessHash):
|
||||
missingUsers.append(.inputUser(userId: userId, accessHash: accessHash))
|
||||
case let .inputPeerUser(inputPeerUserData):
|
||||
let (userId, accessHash) = (inputPeerUserData.userId, inputPeerUserData.accessHash)
|
||||
missingUsers.append(.inputUser(.init(userId: userId, accessHash: accessHash)))
|
||||
case .inputPeerSelf:
|
||||
missingUsers.append(.inputUserSelf)
|
||||
case let .inputPeerChannel(channelId, accessHash):
|
||||
missingChannels.append(.inputChannel(channelId: channelId, accessHash: accessHash))
|
||||
case let .inputPeerChat(id):
|
||||
case let .inputPeerChannel(inputPeerChannelData):
|
||||
let (channelId, accessHash) = (inputPeerChannelData.channelId, inputPeerChannelData.accessHash)
|
||||
missingChannels.append(.inputChannel(.init(channelId: channelId, accessHash: accessHash)))
|
||||
case let .inputPeerChat(inputPeerChatData):
|
||||
let id = inputPeerChatData.chatId
|
||||
missingGroups.append(id)
|
||||
case .inputPeerEmpty:
|
||||
break
|
||||
@@ -713,7 +751,11 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
if let result = result {
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case .chats(let chats), .chatsSlice(_, let chats):
|
||||
case let .chats(chatsData):
|
||||
let chats = chatsData.chats
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let chats = chatsSliceData.chats
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
}
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
@@ -737,7 +779,11 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
if let result = result {
|
||||
let parsedPeers: AccumulatedPeers
|
||||
switch result {
|
||||
case .chats(let chats), .chatsSlice(_, let chats):
|
||||
case let .chats(chatsData):
|
||||
let chats = chatsData.chats
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let chats = chatsSliceData.chats
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: [])
|
||||
}
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
@@ -779,7 +825,7 @@ private func requestChatListFilters(accountPeerId: PeerId, postbox: Postbox, net
|
||||
}
|
||||
|
||||
private func loadAndStorePeerChatInfos(accountPeerId: PeerId, postbox: Postbox, network: Network, peers: [Api.InputPeer]) -> Signal<Never, NoError> {
|
||||
let signal = network.request(Api.functions.messages.getPeerDialogs(peers: peers.map(Api.InputDialogPeer.inputDialogPeer(peer:))))
|
||||
let signal = network.request(Api.functions.messages.getPeerDialogs(peers: peers.map { .inputDialogPeer(.init(peer: $0)) }))
|
||||
|> map(Optional.init)
|
||||
|
||||
return signal
|
||||
@@ -799,14 +845,16 @@ private func loadAndStorePeerChatInfos(accountPeerId: PeerId, postbox: Postbox,
|
||||
let parsedPeers: AccumulatedPeers
|
||||
|
||||
switch result {
|
||||
case let .peerDialogs(dialogs, messages, chats, users, _):
|
||||
case let .peerDialogs(peerDialogsData):
|
||||
let (dialogs, messages, chats, users, _) = (peerDialogsData.dialogs, peerDialogsData.messages, peerDialogsData.chats, peerDialogsData.users, peerDialogsData.state)
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
var topMessageIds = Set<MessageId>()
|
||||
|
||||
for dialog in dialogs {
|
||||
switch dialog {
|
||||
case let .dialog(_, peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, notifySettings, pts, _, folderId, ttlPeriod):
|
||||
case let .dialog(dialogData):
|
||||
let (peer, topMessage, readInboxMaxId, readOutboxMaxId, unreadCount, unreadMentionsCount, unreadReactionsCount, notifySettings, pts, folderId, ttlPeriod) = (dialogData.peer, dialogData.topMessage, dialogData.readInboxMaxId, dialogData.readOutboxMaxId, dialogData.unreadCount, dialogData.unreadMentionsCount, dialogData.unreadReactionsCount, dialogData.notifySettings, dialogData.pts, dialogData.folderId, dialogData.ttlPeriod)
|
||||
let peerId = peer.peerId
|
||||
|
||||
if topMessage != 0 {
|
||||
@@ -1090,13 +1138,18 @@ func _internal_updatedChatListFilters(postbox: Postbox, hiddenIds: Signal<Set<In
|
||||
)
|
||||
|> map { preferences, hiddenIds -> [ChatListFilter] in
|
||||
let filtersState = preferences.values[PreferencesKeys.chatListFilters]?.get(ChatListFiltersState.self) ?? ChatListFiltersState.default
|
||||
return filtersState.filters.filter { filter in
|
||||
var filters = filtersState.filters.filter { filter in
|
||||
if hiddenIds.contains(filter.id) {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// MARK: Swiftgram
|
||||
if filters.count > 1 && SGSimpleSettings.shared.allChatsHidden {
|
||||
filters.removeAll { $0 == .allChats }
|
||||
}
|
||||
return filters
|
||||
}
|
||||
|> distinctUntilChanged
|
||||
}
|
||||
@@ -1269,7 +1322,8 @@ func _internal_updateChatListFeaturedFilters(postbox: Postbox, network: Network)
|
||||
var state = entry?.get(ChatListFiltersFeaturedState.self) ?? ChatListFiltersFeaturedState(filters: [], isSeen: false)
|
||||
state.filters = result.compactMap { item -> ChatListFeaturedFilter? in
|
||||
switch item {
|
||||
case let .dialogFilterSuggested(filter, description):
|
||||
case let .dialogFilterSuggested(dialogFilterSuggestedData):
|
||||
let (filter, description) = (dialogFilterSuggestedData.filter, dialogFilterSuggestedData.description)
|
||||
let parsedFilter = ChatListFilter(apiFilter: filter)
|
||||
if case let .filter(_, title, _, data) = parsedFilter {
|
||||
return ChatListFeaturedFilter(title: title, description: description, data: data)
|
||||
@@ -1603,4 +1657,4 @@ private func synchronizeChatListFilters(transaction: Transaction, accountPeerId:
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ func _internal_chatOnlineMembers(postbox: Postbox, network: Network, peerId: Pee
|
||||
return network.request(Api.functions.messages.getOnlines(peer: inputPeer))
|
||||
|> map { value -> Int32 in
|
||||
switch value {
|
||||
case let .chatOnlines(onlines):
|
||||
case let .chatOnlines(chatOnlinesData):
|
||||
let onlines = chatOnlinesData.onlines
|
||||
return onlines
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func _internal_exportChatFolder(account: Account, filterId: Int32, title: String
|
||||
}
|
||||
|> castError(ExportChatFolderError.self)
|
||||
|> mapToSignal { inputPeers -> Signal<ExportedChatFolderLink, ExportChatFolderError> in
|
||||
return account.network.request(Api.functions.chatlists.exportChatlistInvite(chatlist: .inputChatlistDialogFilter(filterId: filterId), title: title, peers: inputPeers))
|
||||
return account.network.request(Api.functions.chatlists.exportChatlistInvite(chatlist: .inputChatlistDialogFilter(.init(filterId: filterId)), title: title, peers: inputPeers))
|
||||
|> `catch` { error -> Signal<Api.chatlists.ExportedChatlistInvite, ExportChatFolderError> in
|
||||
if error.errorDescription == "INVITES_TOO_MUCH" || error.errorDescription == "CHATLISTS_TOO_MUCH" {
|
||||
return account.postbox.transaction { transaction -> (AppConfiguration, Bool) in
|
||||
@@ -121,7 +121,8 @@ func _internal_exportChatFolder(account: Account, filterId: Int32, title: String
|
||||
|> mapToSignal { result -> Signal<ExportedChatFolderLink, ExportChatFolderError> in
|
||||
return account.postbox.transaction { transaction -> Signal<ExportedChatFolderLink, ExportChatFolderError> in
|
||||
switch result {
|
||||
case let .exportedChatlistInvite(filter, invite):
|
||||
case let .exportedChatlistInvite(exportedChatlistInviteData):
|
||||
let (filter, invite) = (exportedChatlistInviteData.filter, exportedChatlistInviteData.invite)
|
||||
let parsedFilter = ChatListFilter(apiFilter: filter)
|
||||
|
||||
let _ = updateChatListFiltersState(transaction: transaction, { state in
|
||||
@@ -136,7 +137,8 @@ func _internal_exportChatFolder(account: Account, filterId: Int32, title: String
|
||||
})
|
||||
|
||||
switch invite {
|
||||
case let .exportedChatlistInvite(flags, title, url, peers):
|
||||
case let .exportedChatlistInvite(exportedChatlistInviteData):
|
||||
let (flags, title, url, peers) = (exportedChatlistInviteData.flags, exportedChatlistInviteData.title, exportedChatlistInviteData.url, exportedChatlistInviteData.peers)
|
||||
return .single(ExportedChatFolderLink(
|
||||
title: title,
|
||||
link: url,
|
||||
@@ -154,7 +156,7 @@ func _internal_exportChatFolder(account: Account, filterId: Int32, title: String
|
||||
|
||||
func _internal_getExportedChatFolderLinks(account: Account, id: Int32) -> Signal<[ExportedChatFolderLink]?, NoError> {
|
||||
let accountPeerId = account.peerId
|
||||
return account.network.request(Api.functions.chatlists.getExportedInvites(chatlist: .inputChatlistDialogFilter(filterId: id)))
|
||||
return account.network.request(Api.functions.chatlists.getExportedInvites(chatlist: .inputChatlistDialogFilter(.init(filterId: id))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.chatlists.ExportedInvites?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -165,14 +167,16 @@ func _internal_getExportedChatFolderLinks(account: Account, id: Int32) -> Signal
|
||||
}
|
||||
return account.postbox.transaction { transaction -> [ExportedChatFolderLink]? in
|
||||
switch result {
|
||||
case let .exportedInvites(invites, chats, users):
|
||||
case let .exportedInvites(exportedInvitesData):
|
||||
let (invites, chats, users) = (exportedInvitesData.invites, exportedInvitesData.chats, exportedInvitesData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
var result: [ExportedChatFolderLink] = []
|
||||
for invite in invites {
|
||||
switch invite {
|
||||
case let .exportedChatlistInvite(flags, title, url, peers):
|
||||
case let .exportedChatlistInvite(exportedChatlistInviteData):
|
||||
let (flags, title, url, peers) = (exportedChatlistInviteData.flags, exportedChatlistInviteData.title, exportedChatlistInviteData.url, exportedChatlistInviteData.peers)
|
||||
result.append(ExportedChatFolderLink(
|
||||
title: title,
|
||||
link: url,
|
||||
@@ -206,13 +210,14 @@ func _internal_editChatFolderLink(account: Account, filterId: Int32, link: Expor
|
||||
flags |= 1 << 2
|
||||
peers = peerIds.compactMap(transaction.getPeer).compactMap(apiInputPeer)
|
||||
}
|
||||
return account.network.request(Api.functions.chatlists.editExportedInvite(flags: flags, chatlist: .inputChatlistDialogFilter(filterId: filterId), slug: link.slug, title: title, peers: peers))
|
||||
return account.network.request(Api.functions.chatlists.editExportedInvite(flags: flags, chatlist: .inputChatlistDialogFilter(.init(filterId: filterId)), slug: link.slug, title: title, peers: peers))
|
||||
|> mapError { _ -> EditChatFolderLinkError in
|
||||
return .generic
|
||||
}
|
||||
|> map { result in
|
||||
switch result {
|
||||
case let .exportedChatlistInvite(flags, title, url, peers):
|
||||
case let .exportedChatlistInvite(exportedChatlistInviteData):
|
||||
let (flags, title, url, peers) = (exportedChatlistInviteData.flags, exportedChatlistInviteData.title, exportedChatlistInviteData.url, exportedChatlistInviteData.peers)
|
||||
return ExportedChatFolderLink(
|
||||
title: title,
|
||||
link: url,
|
||||
@@ -231,7 +236,7 @@ public enum RevokeChatFolderLinkError {
|
||||
}
|
||||
|
||||
func _internal_deleteChatFolderLink(account: Account, filterId: Int32, link: ExportedChatFolderLink) -> Signal<Never, RevokeChatFolderLinkError> {
|
||||
return account.network.request(Api.functions.chatlists.deleteExportedInvite(chatlist: .inputChatlistDialogFilter(filterId: filterId), slug: link.slug))
|
||||
return account.network.request(Api.functions.chatlists.deleteExportedInvite(chatlist: .inputChatlistDialogFilter(.init(filterId: filterId)), slug: link.slug))
|
||||
|> mapError { error -> RevokeChatFolderLinkError in
|
||||
return .generic
|
||||
}
|
||||
@@ -273,7 +278,8 @@ func _internal_checkChatFolderLink(account: Account, slug: String) -> Signal<Cha
|
||||
|> mapToSignal { result -> Signal<ChatFolderLinkContents, CheckChatFolderLinkError> in
|
||||
return account.postbox.transaction { transaction -> ChatFolderLinkContents in
|
||||
switch result {
|
||||
case let .chatlistInvite(flags, title, emoticon, peers, chats, users):
|
||||
case let .chatlistInvite(chatlistInviteData):
|
||||
let (flags, title, emoticon, peers, chats, users) = (chatlistInviteData.flags, chatlistInviteData.title, chatlistInviteData.emoticon, chatlistInviteData.peers, chatlistInviteData.chats, chatlistInviteData.users)
|
||||
let _ = emoticon
|
||||
|
||||
let disableTitleAnimation = (flags & (1 << 1)) != 0
|
||||
@@ -282,15 +288,16 @@ func _internal_checkChatFolderLink(account: Account, slug: String) -> Signal<Cha
|
||||
var memberCounts: [PeerId: Int] = [:]
|
||||
|
||||
for chat in chats {
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat {
|
||||
if case let .channel(channelData) = chat {
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
memberCounts[chat.peerId] = Int(participantsCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
var resultPeers: [EnginePeer] = []
|
||||
var alreadyMemberPeerIds = Set<EnginePeer.Id>()
|
||||
for peer in peers {
|
||||
@@ -306,26 +313,29 @@ func _internal_checkChatFolderLink(account: Account, slug: String) -> Signal<Cha
|
||||
let titleText: String
|
||||
let titleEntities: [MessageTextEntity]
|
||||
switch title {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
titleText = text
|
||||
titleEntities = messageTextEntitiesFromApiEntities(entities)
|
||||
}
|
||||
|
||||
|
||||
return ChatFolderLinkContents(localFilterId: nil, title: ChatFolderTitle(text: titleText, entities: titleEntities, enableAnimations: !disableTitleAnimation), peers: resultPeers, alreadyMemberPeerIds: alreadyMemberPeerIds, memberCounts: memberCounts)
|
||||
case let .chatlistInviteAlready(filterId, missingPeers, alreadyPeers, chats, users):
|
||||
case let .chatlistInviteAlready(chatlistInviteAlreadyData):
|
||||
let (filterId, missingPeers, alreadyPeers, chats, users) = (chatlistInviteAlreadyData.filterId, chatlistInviteAlreadyData.missingPeers, chatlistInviteAlreadyData.alreadyPeers, chatlistInviteAlreadyData.chats, chatlistInviteAlreadyData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
var memberCounts: [PeerId: Int] = [:]
|
||||
|
||||
for chat in chats {
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat {
|
||||
if case let .channel(channelData) = chat {
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
memberCounts[chat.peerId] = Int(participantsCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
let currentFilters = _internal_currentChatListFilters(transaction: transaction)
|
||||
var currentFilterTitle: ChatFolderTitle?
|
||||
if let index = currentFilters.firstIndex(where: { $0.id == filterId }) {
|
||||
@@ -482,7 +492,8 @@ func _internal_joinChatFolderLink(account: Account, slug: String, peerIds: [Engi
|
||||
|
||||
var folderResult: JoinChatFolderResult?
|
||||
for update in result.allUpdates {
|
||||
if case let .updateDialogFilter(_, id, data) = update {
|
||||
if case let .updateDialogFilter(updateDialogFilterData) = update {
|
||||
let (id, data) = (updateDialogFilterData.id, updateDialogFilterData.filter)
|
||||
if let data = data, case let .filter(_, title, _, _) = ChatListFilter(apiFilter: data) {
|
||||
folderResult = JoinChatFolderResult(folderId: id, title: title, newChatCount: newChatCount)
|
||||
}
|
||||
@@ -586,7 +597,7 @@ func _internal_pollChatFolderUpdatesOnce(account: Account, folderId: Int32) -> S
|
||||
firstTimeFolderUpdates.insert(key)
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.chatlists.getChatlistUpdates(chatlist: .inputChatlistDialogFilter(filterId: folderId)))
|
||||
return account.network.request(Api.functions.chatlists.getChatlistUpdates(chatlist: .inputChatlistDialogFilter(.init(filterId: folderId))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.chatlists.ChatlistUpdates?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -606,21 +617,23 @@ func _internal_pollChatFolderUpdatesOnce(account: Account, folderId: Int32) -> S
|
||||
|> ignoreValues
|
||||
}
|
||||
switch result {
|
||||
case let .chatlistUpdates(missingPeers, chats, users):
|
||||
case let .chatlistUpdates(chatlistUpdatesData):
|
||||
let (missingPeers, chats, users) = (chatlistUpdatesData.missingPeers, chatlistUpdatesData.chats, chatlistUpdatesData.users)
|
||||
return account.postbox.transaction { transaction -> Void in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
var memberCounts: [ChatListFiltersState.ChatListFilterUpdates.MemberCount] = []
|
||||
|
||||
for chat in chats {
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat {
|
||||
if case let .channel(channelData) = chat {
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
memberCounts.append(ChatListFiltersState.ChatListFilterUpdates.MemberCount(id: chat.peerId, count: participantsCount))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
let _ = updateChatListFiltersState(transaction: transaction, { state in
|
||||
var state = state
|
||||
|
||||
@@ -687,7 +700,7 @@ func _internal_joinAvailableChatsInFolder(account: Account, updates: ChatFolderU
|
||||
}
|
||||
|> castError(JoinChatFolderLinkError.self)
|
||||
|> mapToSignal { inputPeers -> Signal<Never, JoinChatFolderLinkError> in
|
||||
return account.network.request(Api.functions.chatlists.joinChatlistUpdates(chatlist: .inputChatlistDialogFilter(filterId: updates.folderId), peers: inputPeers))
|
||||
return account.network.request(Api.functions.chatlists.joinChatlistUpdates(chatlist: .inputChatlistDialogFilter(.init(filterId: updates.folderId)), peers: inputPeers))
|
||||
|> `catch` { error -> Signal<Api.Updates, JoinChatFolderLinkError> in
|
||||
if error.errorDescription == "DIALOG_FILTERS_TOO_MUCH" {
|
||||
return account.postbox.transaction { transaction -> (AppConfiguration, Bool) in
|
||||
@@ -742,7 +755,7 @@ func _internal_hideChatFolderUpdates(account: Account, folderId: Int32) -> Signa
|
||||
})
|
||||
}
|
||||
|> mapToSignal { _ -> Signal<Never, NoError> in
|
||||
return account.network.request(Api.functions.chatlists.hideChatlistUpdates(chatlist: .inputChatlistDialogFilter(filterId: folderId)))
|
||||
return account.network.request(Api.functions.chatlists.hideChatlistUpdates(chatlist: .inputChatlistDialogFilter(.init(filterId: folderId))))
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
return .single(.boolFalse)
|
||||
}
|
||||
@@ -755,7 +768,7 @@ func _internal_leaveChatFolder(account: Account, folderId: Int32, removePeerIds:
|
||||
return removePeerIds.compactMap(transaction.getPeer).compactMap(apiInputPeer)
|
||||
}
|
||||
|> mapToSignal { inputPeers -> Signal<Never, NoError> in
|
||||
return account.network.request(Api.functions.chatlists.leaveChatlist(chatlist: .inputChatlistDialogFilter(filterId: folderId), peers: inputPeers))
|
||||
return account.network.request(Api.functions.chatlists.leaveChatlist(chatlist: .inputChatlistDialogFilter(.init(filterId: folderId)), peers: inputPeers))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.Updates?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -772,7 +785,7 @@ func _internal_leaveChatFolder(account: Account, folderId: Int32, removePeerIds:
|
||||
}
|
||||
|
||||
func _internal_requestLeaveChatFolderSuggestions(account: Account, folderId: Int32) -> Signal<[EnginePeer.Id], NoError> {
|
||||
return account.network.request(Api.functions.chatlists.getLeaveChatlistSuggestions(chatlist: .inputChatlistDialogFilter(filterId: folderId)))
|
||||
return account.network.request(Api.functions.chatlists.getLeaveChatlistSuggestions(chatlist: .inputChatlistDialogFilter(.init(filterId: folderId))))
|
||||
|> map { result -> [EnginePeer.Id] in
|
||||
return result.map(\.peerId)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,8 @@ func _internal_exportContactToken(account: Account) -> Signal<ExportedContactTok
|
||||
return .single(nil)
|
||||
}
|
||||
|> map { result -> ExportedContactToken? in
|
||||
if let result = result, case let .exportedContactToken(url, expires) = result {
|
||||
if let result = result, case let .exportedContactToken(exportedContactTokenData) = result {
|
||||
let (url, expires) = (exportedContactTokenData.url, exportedContactTokenData.expires)
|
||||
return ExportedContactToken(url: url, expires: expires)
|
||||
} else {
|
||||
return nil
|
||||
|
||||
@@ -58,7 +58,8 @@ func _internal_createGroup(account: Account, title: String, peerIds: [PeerId], t
|
||||
let updatesValue: Api.Updates
|
||||
let missingInviteesValue: [Api.MissingInvitee]
|
||||
switch result {
|
||||
case let .invitedUsers(updates, missingInvitees):
|
||||
case let .invitedUsers(invitedUsersData):
|
||||
let (updates, missingInvitees) = (invitedUsersData.updates, invitedUsersData.missingInvitees)
|
||||
updatesValue = updates
|
||||
missingInviteesValue = missingInvitees
|
||||
}
|
||||
@@ -77,7 +78,8 @@ func _internal_createGroup(account: Account, title: String, peerIds: [PeerId], t
|
||||
peerId: peerId,
|
||||
result: TelegramInvitePeersResult(forbiddenPeers: missingInviteesValue.compactMap { invitee -> TelegramForbiddenInvitePeer? in
|
||||
switch invitee {
|
||||
case let .missingInvitee(flags, userId):
|
||||
case let .missingInvitee(missingInviteeData):
|
||||
let (flags, userId) = (missingInviteeData.flags, missingInviteeData.userId)
|
||||
guard let peer = transaction.getPeer(PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import Postbox
|
||||
import TelegramApi
|
||||
|
||||
func _internal_findChannelById(accountPeerId: PeerId, postbox: Postbox, network: Network, channelId: Int64) -> Signal<Peer?, NoError> {
|
||||
return network.request(Api.functions.channels.getChannels(id: [.inputChannel(channelId: channelId, accessHash: 0)]))
|
||||
return network.request(Api.functions.channels.getChannels(id: [.inputChannel(.init(channelId: channelId, accessHash: 0))]))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.messages.Chats?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -16,9 +16,11 @@ func _internal_findChannelById(accountPeerId: PeerId, postbox: Postbox, network:
|
||||
}
|
||||
let chats: [Api.Chat]
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
case let .chatsSlice(_, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let (_, apiChats) = (chatsSliceData.count, chatsSliceData.chats)
|
||||
chats = apiChats
|
||||
}
|
||||
guard let id = chats.first?.peerId else {
|
||||
|
||||
@@ -108,10 +108,12 @@ private final class GroupsInCommonContextImpl {
|
||||
let count: Int?
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .chats(apiChats):
|
||||
case let .chats(chatsData):
|
||||
let apiChats = chatsData.chats
|
||||
chats = apiChats
|
||||
count = nil
|
||||
case let .chatsSlice(apiCount, apiChats):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let (apiCount, apiChats) = (chatsSliceData.count, chatsSliceData.chats)
|
||||
chats = apiChats
|
||||
count = Int(apiCount)
|
||||
}
|
||||
|
||||
@@ -24,14 +24,16 @@ func _internal_inactiveChannelList(network: Network) -> Signal<[InactiveChannel]
|
||||
|> retryRequest
|
||||
|> map { result in
|
||||
switch result {
|
||||
case let .inactiveChats(dates, chats, _):
|
||||
case let .inactiveChats(inactiveChatsData):
|
||||
let (dates, chats) = (inactiveChatsData.dates, inactiveChatsData.chats)
|
||||
let channels = chats.compactMap {
|
||||
parseTelegramGroupOrChannel(chat: $0)
|
||||
}
|
||||
var participantsCounts: [PeerId: Int32] = [:]
|
||||
for chat in chats {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCountValue, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCountValue = channelData.participantsCount
|
||||
if let participantsCountValue = participantsCountValue {
|
||||
participantsCounts[chat.peerId] = participantsCountValue
|
||||
}
|
||||
|
||||
@@ -147,7 +147,8 @@ func _internal_editPeerExportedInvitation(account: Account, peerId: PeerId, link
|
||||
|> mapError { _ in return EditPeerExportedInvitationError.generic }
|
||||
|> mapToSignal { result -> Signal<ExportedInvitation?, EditPeerExportedInvitationError> in
|
||||
return account.postbox.transaction { transaction in
|
||||
if case let .exportedChatInvite(invite, users) = result {
|
||||
if case let .exportedChatInvite(exportedChatInviteData) = result {
|
||||
let (invite, users) = (exportedChatInviteData.invite, exportedChatInviteData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
return ExportedInvitation(apiExportedInvite: invite)
|
||||
} else {
|
||||
@@ -181,10 +182,12 @@ func _internal_revokePeerExportedInvitation(account: Account, peerId: PeerId, li
|
||||
|> mapError { _ in return RevokePeerExportedInvitationError.generic }
|
||||
|> mapToSignal { result -> Signal<RevokeExportedInvitationResult?, RevokePeerExportedInvitationError> in
|
||||
return account.postbox.transaction { transaction in
|
||||
if case let .exportedChatInvite(invite, users) = result {
|
||||
if case let .exportedChatInvite(exportedChatInviteData) = result {
|
||||
let (invite, users) = (exportedChatInviteData.invite, exportedChatInviteData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
return .update(ExportedInvitation(apiExportedInvite: invite))
|
||||
} else if case let .exportedChatInviteReplaced(invite, newInvite, users) = result {
|
||||
} else if case let .exportedChatInviteReplaced(exportedChatInviteReplacedData) = result {
|
||||
let (invite, newInvite, users) = (exportedChatInviteReplacedData.invite, exportedChatInviteReplacedData.newInvite, exportedChatInviteReplacedData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
|
||||
let previous = ExportedInvitation(apiExportedInvite: invite)
|
||||
@@ -243,7 +246,8 @@ func _internal_peerExportedInvitations(account: Account, peerId: PeerId, revoked
|
||||
}
|
||||
|> mapToSignal { result -> Signal<ExportedInvitations?, NoError> in
|
||||
return account.postbox.transaction { transaction -> ExportedInvitations? in
|
||||
if let result = result, case let .exportedChatInvites(count, apiInvites, users) = result {
|
||||
if let result = result, case let .exportedChatInvites(exportedChatInvitesData) = result {
|
||||
let (count, apiInvites, users) = (exportedChatInvitesData.count, exportedChatInvitesData.invites, exportedChatInvitesData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -465,7 +469,8 @@ private final class PeerExportedInvitationsContextImpl {
|
||||
return ([], 0)
|
||||
}
|
||||
switch result {
|
||||
case let .exportedChatInvites(count, invites, users):
|
||||
case let .exportedChatInvites(exportedChatInvitesData):
|
||||
let (count, invites, users) = (exportedChatInvitesData.count, exportedChatInvitesData.invites, exportedChatInvitesData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
let invitations: [ExportedInvitation] = invites.compactMap { ExportedInvitation(apiExportedInvite: $0) }
|
||||
if populateCache {
|
||||
@@ -948,7 +953,8 @@ private final class PeerInvitationImportersContextImpl {
|
||||
return ([], 0)
|
||||
}
|
||||
switch result {
|
||||
case let .chatInviteImporters(count, importers, users):
|
||||
case let .chatInviteImporters(chatInviteImportersData):
|
||||
let (count, importers, users) = (chatInviteImportersData.count, chatInviteImportersData.importers, chatInviteImportersData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: AccumulatedPeers(users: users))
|
||||
var resultImporters: [PeerInvitationImportersState.Importer] = []
|
||||
for importer in importers {
|
||||
@@ -958,7 +964,8 @@ private final class PeerInvitationImportersContextImpl {
|
||||
let approvedBy: PeerId?
|
||||
let joinedViaFolderLink: Bool
|
||||
switch importer {
|
||||
case let .chatInviteImporter(flags, userId, dateValue, aboutValue, approvedByValue):
|
||||
case let .chatInviteImporter(chatInviteImporterData):
|
||||
let (flags, userId, dateValue, aboutValue, approvedByValue) = (chatInviteImporterData.flags, chatInviteImporterData.userId, chatInviteImporterData.date, chatInviteImporterData.about, chatInviteImporterData.approvedBy)
|
||||
joinedViaFolderLink = (flags & (1 << 3)) != 0
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
date = dateValue
|
||||
@@ -1161,14 +1168,16 @@ func _internal_peerExportedInvitationsCreators(account: Account, peerId: PeerId)
|
||||
}
|
||||
|> mapToSignal { result -> Signal<[ExportedInvitationCreator], NoError> in
|
||||
return account.postbox.transaction { transaction -> [ExportedInvitationCreator] in
|
||||
if let result = result, case let .chatAdminsWithInvites(admins, users) = result {
|
||||
if let result = result, case let .chatAdminsWithInvites(chatAdminsWithInvitesData) = result {
|
||||
let (admins, users) = (chatAdminsWithInvitesData.admins, chatAdminsWithInvitesData.users)
|
||||
var creators: [ExportedInvitationCreator] = []
|
||||
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: users)
|
||||
|
||||
for admin in admins {
|
||||
switch admin {
|
||||
case let .chatAdminWithInvites(adminId, invitesCount, revokedInvitesCount):
|
||||
case let .chatAdminWithInvites(chatAdminWithInvitesData):
|
||||
let (adminId, invitesCount, revokedInvitesCount) = (chatAdminWithInvitesData.adminId, chatAdminWithInvitesData.invitesCount, chatAdminWithInvitesData.revokedInvitesCount)
|
||||
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(adminId))
|
||||
if let peer = parsedPeers.get(peerId), peerId != account.peerId {
|
||||
creators.append(ExportedInvitationCreator(peer: RenderedPeer(peer: peer), count: invitesCount, revokedCount: revokedInvitesCount))
|
||||
|
||||
@@ -67,7 +67,8 @@ func _internal_joinChannel(account: Account, peerId: PeerId, hash: String?) -> S
|
||||
}
|
||||
let updatedParticipant: ChannelParticipant
|
||||
switch result {
|
||||
case let .channelParticipant(participant, _, _):
|
||||
case let .channelParticipant(channelParticipantData):
|
||||
let participant = channelParticipantData.participant
|
||||
updatedParticipant = ChannelParticipant(apiParticipant: participant)
|
||||
}
|
||||
if case let .member(_, _, maybeAdminInfo, _, _, _) = updatedParticipant {
|
||||
|
||||
@@ -19,9 +19,11 @@ public enum JoinLinkError {
|
||||
|
||||
func apiUpdatesGroups(_ updates: Api.Updates) -> [Api.Chat] {
|
||||
switch updates {
|
||||
case let .updates( _, _, chats, _, _):
|
||||
case let .updates(updatesData):
|
||||
let chats = updatesData.chats
|
||||
return chats
|
||||
case let .updatesCombined(_, _, chats, _, _, _):
|
||||
case let .updatesCombined(updatesCombinedData):
|
||||
let chats = updatesCombinedData.chats
|
||||
return chats
|
||||
default:
|
||||
return []
|
||||
@@ -110,11 +112,13 @@ func _internal_joinLinkInformation(_ hash: String, account: Account) -> Signal<E
|
||||
|> mapToSignal { result -> Signal<ExternalJoiningChatState, JoinLinkInfoError> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .chatInvite(flags, title, about, invitePhoto, participantsCount, participants, nameColor, subscriptionPricing, subscriptionFormId, verification):
|
||||
case let .chatInvite(chatInviteData):
|
||||
let (apiFlags, title, about, invitePhoto, participantsCount, participants, nameColor, subscriptionPricing, subscriptionFormId, verification) = (chatInviteData.flags, chatInviteData.title, chatInviteData.about, chatInviteData.photo, chatInviteData.participantsCount, chatInviteData.participants, chatInviteData.color, chatInviteData.subscriptionPricing, chatInviteData.subscriptionFormId, chatInviteData.botVerification)
|
||||
let photo = telegramMediaImageFromApiPhoto(invitePhoto).flatMap({ smallestImageRepresentation($0.representations) })
|
||||
let flags: ExternalJoiningChatState.Invite.Flags = .init(isChannel: (flags & (1 << 0)) != 0, isBroadcast: (flags & (1 << 1)) != 0, isPublic: (flags & (1 << 2)) != 0, isMegagroup: (flags & (1 << 3)) != 0, requestNeeded: (flags & (1 << 6)) != 0, isVerified: (flags & (1 << 7)) != 0, isScam: (flags & (1 << 8)) != 0, isFake: (flags & (1 << 9)) != 0, canRefulfillSubscription: (flags & (1 << 11)) != 0)
|
||||
let flags: ExternalJoiningChatState.Invite.Flags = .init(isChannel: (apiFlags & (1 << 0)) != 0, isBroadcast: (apiFlags & (1 << 1)) != 0, isPublic: (apiFlags & (1 << 2)) != 0, isMegagroup: (apiFlags & (1 << 3)) != 0, requestNeeded: (apiFlags & (1 << 6)) != 0, isVerified: (apiFlags & (1 << 7)) != 0, isScam: (apiFlags & (1 << 8)) != 0, isFake: (apiFlags & (1 << 9)) != 0, canRefulfillSubscription: (apiFlags & (1 << 11)) != 0)
|
||||
return .single(.invite(ExternalJoiningChatState.Invite(flags: flags, title: title, about: about, photoRepresentation: photo, participantsCount: participantsCount, participants: participants?.map({ EnginePeer(TelegramUser(user: $0)) }), nameColor: PeerNameColor(rawValue: nameColor), subscriptionPricing: subscriptionPricing.flatMap { StarsSubscriptionPricing(apiStarsSubscriptionPricing: $0) }, subscriptionFormId: subscriptionFormId, verification: verification.flatMap { PeerVerification(apiBotVerification: $0) })))
|
||||
case let .chatInviteAlready(chat):
|
||||
case let .chatInviteAlready(chatInviteAlreadyData):
|
||||
let chat = chatInviteAlreadyData.chat
|
||||
if let peer = parseTelegramGroupOrChannel(chat: chat) {
|
||||
return account.postbox.transaction({ (transaction) -> ExternalJoiningChatState in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [chat], users: [])
|
||||
@@ -124,7 +128,8 @@ func _internal_joinLinkInformation(_ hash: String, account: Account) -> Signal<E
|
||||
|> castError(JoinLinkInfoError.self)
|
||||
}
|
||||
return .single(.invalidHash)
|
||||
case let .chatInvitePeek(chat, expires):
|
||||
case let .chatInvitePeek(chatInvitePeekData):
|
||||
let (chat, expires) = (chatInvitePeekData.chat, chatInvitePeekData.expires)
|
||||
if let peer = parseTelegramGroupOrChannel(chat: chat) {
|
||||
return account.postbox.transaction({ (transaction) -> ExternalJoiningChatState in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [chat], users: [])
|
||||
|
||||
+4
-2
@@ -16,9 +16,11 @@ func _internal_availableGroupsForChannelDiscussion(accountPeerId: PeerId, postbo
|
||||
|> mapToSignal { result -> Signal<[Peer], AvailableChannelDiscussionGroupError> in
|
||||
let chats: [Api.Chat]
|
||||
switch result {
|
||||
case let .chats(c):
|
||||
case let .chats(chatsData):
|
||||
let c = chatsData.chats
|
||||
chats = c
|
||||
case let .chatsSlice(_, c):
|
||||
case let .chatsSlice(chatsSliceData):
|
||||
let c = chatsSliceData.chats
|
||||
chats = c
|
||||
}
|
||||
|
||||
|
||||
+15
-9
@@ -34,31 +34,37 @@ func _internal_notificationExceptionsList(accountPeerId: PeerId, postbox: Postbo
|
||||
}
|
||||
return postbox.transaction { transaction -> NotificationExceptionsList in
|
||||
switch result {
|
||||
case let .updates(updates, users, chats, _, _):
|
||||
case let .updates(updatesData):
|
||||
let (updates, users, chats) = (updatesData.updates, updatesData.users, updatesData.chats)
|
||||
var settings: [PeerId: TelegramPeerNotificationSettings] = [:]
|
||||
|
||||
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId,peers: parsedPeers)
|
||||
|
||||
|
||||
var peers: [PeerId: Peer] = [:]
|
||||
for id in parsedPeers.allIds {
|
||||
if let peer = transaction.getPeer(id) {
|
||||
peers[peer.id] = peer
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for update in updates {
|
||||
switch update {
|
||||
case let .updateNotifySettings(apiPeer, notifySettings):
|
||||
case let .updateNotifySettings(updateNotifySettingsData):
|
||||
let (apiPeer, notifySettings) = (updateNotifySettingsData.peer, updateNotifySettingsData.notifySettings)
|
||||
switch apiPeer {
|
||||
case let .notifyPeer(notifyPeer):
|
||||
case let .notifyPeer(notifyPeerData):
|
||||
let notifyPeer = notifyPeerData.peer
|
||||
let peerId: PeerId
|
||||
switch notifyPeer {
|
||||
case let .peerUser(userId):
|
||||
case let .peerUser(peerUserData):
|
||||
let userId = peerUserData.userId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
case let .peerChat(chatId):
|
||||
case let .peerChat(peerChatData):
|
||||
let chatId = peerChatData.chatId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(chatId))
|
||||
case let .peerChannel(channelId):
|
||||
case let .peerChannel(peerChannelData):
|
||||
let channelId = peerChannelData.channelId
|
||||
peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: PeerId.Id._internalFromInt64Value(channelId))
|
||||
}
|
||||
settings[peerId] = TelegramPeerNotificationSettings(apiSettings: notifySettings)
|
||||
|
||||
@@ -180,7 +180,8 @@ func requestNotificationSoundList(network: Network, hash: Int64) -> Signal<Notif
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .savedRingtones(hash, ringtones):
|
||||
case let .savedRingtones(savedRingtonesData):
|
||||
let (hash, ringtones) = (savedRingtonesData.hash, savedRingtonesData.ringtones)
|
||||
let notificationSoundList = NotificationSoundList(
|
||||
hash: hash,
|
||||
sounds: ringtones.compactMap(NotificationSoundList.NotificationSound.init(apiDocument:))
|
||||
@@ -207,7 +208,8 @@ private func pollNotificationSoundList(postbox: Postbox, network: Network) -> Si
|
||||
return .complete()
|
||||
}
|
||||
switch result {
|
||||
case let .savedRingtones(hash, ringtones):
|
||||
case let .savedRingtones(savedRingtonesData):
|
||||
let (hash, ringtones) = (savedRingtonesData.hash, savedRingtonesData.ringtones)
|
||||
let notificationSoundList = NotificationSoundList(
|
||||
hash: hash,
|
||||
sounds: ringtones.compactMap(NotificationSoundList.NotificationSound.init(apiDocument:))
|
||||
@@ -269,7 +271,7 @@ func _internal_saveNotificationSound(account: Account, file: FileMediaReference,
|
||||
return .fail(.generic)
|
||||
}
|
||||
let accountPeerId = account.peerId
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), unsave: unsave ? .boolTrue : .boolFalse))
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), unsave: unsave ? .boolTrue : .boolFalse))
|
||||
|> `catch` { error -> Signal<Api.account.SavedRingtone, MTRpcError> in
|
||||
if error.errorDescription == "FILE_REFERENCE_EXPIRED" {
|
||||
return revalidateMediaResourceReference(accountPeerId: accountPeerId, postbox: account.postbox, network: account.network, revalidationContext: account.mediaReferenceRevalidationContext, info: TelegramCloudMediaResourceFetchInfo(reference: file.abstract.resourceReference(file.media.resource), preferBackgroundReferenceRevalidation: false, continueInBackground: false), resource: file.media.resource)
|
||||
@@ -280,8 +282,8 @@ func _internal_saveNotificationSound(account: Account, file: FileMediaReference,
|
||||
guard let resource = result.updatedResource as? CloudDocumentMediaResource else {
|
||||
return .fail(MTRpcError(errorCode: 500, errorDescription: "Internal"))
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), unsave: unsave ? .boolTrue : .boolFalse))
|
||||
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), unsave: unsave ? .boolTrue : .boolFalse))
|
||||
}
|
||||
} else {
|
||||
return .fail(error)
|
||||
@@ -354,7 +356,7 @@ func _internal_deleteNotificationSound(account: Account, fileId: Int64) -> Signa
|
||||
return .fail(.generic)
|
||||
}
|
||||
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), unsave: .boolTrue))
|
||||
return account.network.request(Api.functions.account.saveRingtone(id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), unsave: .boolTrue))
|
||||
|> mapError { _ -> DeleteNotificationSoundError in
|
||||
return .generic
|
||||
}
|
||||
|
||||
@@ -133,7 +133,8 @@ func _internal_fetchChannelParticipant(account: Account, peerId: PeerId, partici
|
||||
return account.network.request(Api.functions.channels.getParticipant(channel: inputChannel, participant: inputPeer))
|
||||
|> map { result -> ChannelParticipant? in
|
||||
switch result {
|
||||
case let .channelParticipant(participant, _, _):
|
||||
case let .channelParticipant(channelParticipantData):
|
||||
let participant = channelParticipantData.participant
|
||||
return ChannelParticipant(apiParticipant: participant)
|
||||
}
|
||||
}
|
||||
@@ -183,7 +184,7 @@ func _internal_updateChannelAdminRights(account: Account, peerId: PeerId, adminI
|
||||
}
|
||||
updatedParticipant = .member(id: adminId, invitedAt: Int32(Date().timeIntervalSince1970), adminInfo: adminInfo, banInfo: nil, rank: rank, subscriptionUntilDate: nil)
|
||||
}
|
||||
return account.network.request(Api.functions.channels.editAdmin(channel: inputChannel, userId: inputUser, adminRights: rights?.apiAdminRights ?? .chatAdminRights(flags: 0), rank: rank ?? ""))
|
||||
return account.network.request(Api.functions.channels.editAdmin(channel: inputChannel, userId: inputUser, adminRights: rights?.apiAdminRights ?? .chatAdminRights(Api.ChatAdminRights.Cons_chatAdminRights(flags: 0)), rank: rank ?? ""))
|
||||
|> map { [$0] }
|
||||
|> `catch` { error -> Signal<[Api.Updates], UpdateChannelAdminRightsError> in
|
||||
if error.errorDescription == "USER_NOT_PARTICIPANT" {
|
||||
@@ -195,7 +196,7 @@ func _internal_updateChannelAdminRights(account: Account, peerId: PeerId, adminI
|
||||
return .addMemberError(error)
|
||||
}
|
||||
|> then(
|
||||
account.network.request(Api.functions.channels.editAdmin(channel: inputChannel, userId: inputUser, adminRights: rights?.apiAdminRights ?? .chatAdminRights(flags: 0), rank: rank ?? ""))
|
||||
account.network.request(Api.functions.channels.editAdmin(channel: inputChannel, userId: inputUser, adminRights: rights?.apiAdminRights ?? .chatAdminRights(Api.ChatAdminRights.Cons_chatAdminRights(flags: 0)), rank: rank ?? ""))
|
||||
|> mapError { error -> UpdateChannelAdminRightsError in
|
||||
return .generic
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ public struct UploadedPeerPhotoData {
|
||||
}
|
||||
|
||||
static func withResource(_ resource: MediaResource) -> UploadedPeerPhotoData {
|
||||
return UploadedPeerPhotoData(resource: resource, content: .result(.inputFile(.inputFile(id: 0, parts: 0, name: "", md5Checksum: ""))), local: true)
|
||||
return UploadedPeerPhotoData(resource: resource, content: .result(.inputFile(.inputFile(.init(id: 0, parts: 0, name: "", md5Checksum: "")))), local: true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,9 +109,9 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
if let markup = markup {
|
||||
switch markup {
|
||||
case let .emoji(fileId, backgroundColors):
|
||||
videoEmojiMarkup = .videoSizeEmojiMarkup(emojiId: fileId, backgroundColors: backgroundColors)
|
||||
videoEmojiMarkup = .videoSizeEmojiMarkup(.init(emojiId: fileId, backgroundColors: backgroundColors))
|
||||
case let .sticker(packReference, fileId, backgroundColors):
|
||||
videoEmojiMarkup = .videoSizeStickerMarkup(stickerset: packReference.apiInputStickerSet, stickerId: fileId, backgroundColors: backgroundColors)
|
||||
videoEmojiMarkup = .videoSizeStickerMarkup(.init(stickerset: packReference.apiInputStickerSet, stickerId: fileId, backgroundColors: backgroundColors))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +164,8 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
case let .progress(progress):
|
||||
let mappedProgress = 0.2 + progress * 0.8
|
||||
return .single((.progress(mappedProgress), photoResult.resource, videoResult.resource))
|
||||
case let .inputFile(file):
|
||||
videoFile = file
|
||||
case let .inputFile(videoInputFile):
|
||||
videoFile = videoInputFile
|
||||
break
|
||||
default:
|
||||
return .fail(.generic)
|
||||
@@ -235,22 +235,26 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
var videoRepresentations: [TelegramMediaImage.VideoRepresentation] = []
|
||||
var image: TelegramMediaImage?
|
||||
switch photo {
|
||||
case let .photo(apiPhoto, _):
|
||||
case let .photo(photoData):
|
||||
let (apiPhoto, _) = (photoData.photo, photoData.users)
|
||||
image = telegramMediaImageFromApiPhoto(apiPhoto)
|
||||
switch apiPhoto {
|
||||
case .photoEmpty:
|
||||
break
|
||||
case let .photo(_, id, accessHash, fileReference, _, sizes, videoSizes, dcId):
|
||||
var sizes = sizes
|
||||
case let .photo(photoData):
|
||||
let (id, accessHash, fileReference, apiSizes, videoSizes, dcId) = (photoData.id, photoData.accessHash, photoData.fileReference, photoData.sizes, photoData.videoSizes, photoData.dcId)
|
||||
var sizes = apiSizes
|
||||
if sizes.count == 3 {
|
||||
sizes.remove(at: 1)
|
||||
}
|
||||
for size in sizes {
|
||||
switch size {
|
||||
case let .photoSize(_, w, h, _):
|
||||
case let .photoSize(photoSizeData):
|
||||
let (w, h) = (photoSizeData.w, photoSizeData.h)
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
case let .photoSizeProgressive(_, w, h, sizes):
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: sizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
case let .photoSizeProgressive(photoSizeProgressiveData):
|
||||
let (w, h, progressiveSizes) = (photoSizeProgressiveData.w, photoSizeProgressiveData.h, photoSizeProgressiveData.sizes)
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: progressiveSizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -259,10 +263,11 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
if let videoSizes = videoSizes {
|
||||
for size in videoSizes {
|
||||
switch size {
|
||||
case let .videoSize(_, type, w, h, size, videoStartTs):
|
||||
case let .videoSize(videoSizeData):
|
||||
let (_, type, w, h, size, videoStartTs) = (videoSizeData.flags, videoSizeData.type, videoSizeData.w, videoSizeData.h, videoSizeData.size, videoSizeData.videoStartTs)
|
||||
let resource: TelegramMediaResource
|
||||
resource = CloudPhotoSizeMediaResource(datacenterId: dcId, photoId: id, accessHash: accessHash, sizeSpec: type, size: Int64(size), fileReference: fileReference.makeData())
|
||||
|
||||
|
||||
videoRepresentations.append(TelegramMediaImage.VideoRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: resource, startTimestamp: videoStartTs))
|
||||
case .videoSizeEmojiMarkup, .videoSizeStickerMarkup:
|
||||
break
|
||||
@@ -339,9 +344,9 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
|
||||
let request: Signal<Api.Updates, MTRpcError>
|
||||
if let peer = peer as? TelegramGroup {
|
||||
request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id._internalGetInt64Value(), photo: .inputChatUploadedPhoto(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp, videoEmojiMarkup: videoEmojiMarkup)))
|
||||
request = network.request(Api.functions.messages.editChatPhoto(chatId: peer.id.id._internalGetInt64Value(), photo: .inputChatUploadedPhoto(.init(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp, videoEmojiMarkup: videoEmojiMarkup))))
|
||||
} else if let peer = peer as? TelegramChannel, let inputChannel = apiInputChannel(peer) {
|
||||
request = network.request(Api.functions.channels.editPhoto(channel: inputChannel, photo: .inputChatUploadedPhoto(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp, videoEmojiMarkup: videoEmojiMarkup)))
|
||||
request = network.request(Api.functions.channels.editPhoto(channel: inputChannel, photo: .inputChatUploadedPhoto(.init(flags: flags, file: file, video: videoFile, videoStartTs: videoStartTimestamp, videoEmojiMarkup: videoEmojiMarkup))))
|
||||
} else {
|
||||
assertionFailure()
|
||||
request = .complete()
|
||||
@@ -447,22 +452,26 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
var updatedImage: TelegramMediaImage?
|
||||
var representations: [TelegramMediaImageRepresentation] = []
|
||||
switch photo {
|
||||
case let .photo(apiPhoto, _):
|
||||
case let .photo(photoData):
|
||||
let (apiPhoto, _) = (photoData.photo, photoData.users)
|
||||
updatedImage = telegramMediaImageFromApiPhoto(apiPhoto)
|
||||
switch apiPhoto {
|
||||
case .photoEmpty:
|
||||
break
|
||||
case let .photo(_, id, _, _, _, sizes, _, dcId):
|
||||
var sizes = sizes
|
||||
case let .photo(photoData):
|
||||
let (id, apiSizes, dcId) = (photoData.id, photoData.sizes, photoData.dcId)
|
||||
var sizes = apiSizes
|
||||
if sizes.count == 3 {
|
||||
sizes.remove(at: 1)
|
||||
}
|
||||
for size in sizes {
|
||||
switch size {
|
||||
case let .photoSize(_, w, h, _):
|
||||
case let .photoSize(photoSizeData):
|
||||
let (w, h) = (photoSizeData.w, photoSizeData.h)
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
case let .photoSizeProgressive(_, w, h, sizes):
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: sizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
case let .photoSizeProgressive(photoSizeProgressiveData):
|
||||
let (w, h, progressiveSizes) = (photoSizeProgressiveData.w, photoSizeProgressiveData.h, photoSizeProgressiveData.sizes)
|
||||
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: w, height: h), resource: CloudPeerPhotoSizeMediaResource(datacenterId: dcId, photoId: id, sizeSpec: w <= 200 ? .small : .fullSize, volumeId: nil, localId: nil), progressiveSizes: progressiveSizes, immediateThumbnailData: nil, hasVideo: false, isPersonal: false))
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -495,7 +504,8 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
} else {
|
||||
var updatedUsers: [TelegramUser] = []
|
||||
switch photo {
|
||||
case let .photo(_, apiUsers):
|
||||
case let .photo(photoData):
|
||||
let (_, apiUsers) = (photoData.photo, photoData.users)
|
||||
updatedUsers = apiUsers.map { TelegramUser(user: $0) }
|
||||
}
|
||||
return postbox.transaction { transaction -> UpdatePeerPhotoStatus in
|
||||
@@ -573,12 +583,13 @@ func _internal_updatePeerPhotoInternal(postbox: Postbox, network: Network, state
|
||||
func _internal_updatePeerPhotoExisting(network: Network, reference: TelegramMediaImageReference) -> Signal<TelegramMediaImage?, NoError> {
|
||||
switch reference {
|
||||
case let .cloud(imageId, accessHash, fileReference):
|
||||
return network.request(Api.functions.photos.updateProfilePhoto(flags: 0, bot: nil, id: .inputPhoto(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference))))
|
||||
return network.request(Api.functions.photos.updateProfilePhoto(flags: 0, bot: nil, id: .inputPhoto(.init(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference)))))
|
||||
|> `catch` { _ -> Signal<Api.photos.Photo, NoError> in
|
||||
return .complete()
|
||||
}
|
||||
|> mapToSignal { photo -> Signal<TelegramMediaImage?, NoError> in
|
||||
if case let .photo(photo, _) = photo {
|
||||
if case let .photo(photoData) = photo {
|
||||
let (photo, _) = (photoData.photo, photoData.users)
|
||||
return .single(telegramMediaImageFromApiPhoto(photo))
|
||||
} else {
|
||||
return .complete()
|
||||
@@ -592,7 +603,7 @@ func _internal_removeAccountPhoto(account: Account, reference: TelegramMediaImag
|
||||
switch reference {
|
||||
case let .cloud(imageId, accessHash, fileReference):
|
||||
if let fileReference = fileReference {
|
||||
return account.network.request(Api.functions.photos.deletePhotos(id: [.inputPhoto(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference))]))
|
||||
return account.network.request(Api.functions.photos.deletePhotos(id: [.inputPhoto(.init(id: imageId, accessHash: accessHash, fileReference: Buffer(data: fileReference)))]))
|
||||
|> `catch` { _ -> Signal<[Int64], NoError> in
|
||||
return .single([])
|
||||
}
|
||||
|
||||
@@ -68,7 +68,8 @@ public func _internal_managedUpdatedRecentPeers(accountPeerId: PeerId, postbox:
|
||||
|> mapToSignal { result -> Signal<Void, NoError> in
|
||||
return postbox.transaction { transaction -> Void in
|
||||
switch result {
|
||||
case let .topPeers(_, _, users):
|
||||
case let .topPeers(topPeersData):
|
||||
let users = topPeersData.users
|
||||
let parsedPeers = AccumulatedPeers(users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -156,16 +157,19 @@ func _internal_managedRecentlyUsedInlineBots(postbox: Postbox, network: Network,
|
||||
switch result {
|
||||
case .topPeersDisabled:
|
||||
break
|
||||
case let .topPeers(categories, _, users):
|
||||
case let .topPeers(topPeersData):
|
||||
let (categories, users) = (topPeersData.categories, topPeersData.users)
|
||||
let parsedPeers = AccumulatedPeers(users: users)
|
||||
|
||||
var peersWithRating: [(PeerId, Double)] = []
|
||||
for category in categories {
|
||||
switch category {
|
||||
case let .topPeerCategoryPeers(_, _, topPeers):
|
||||
case let .topPeerCategoryPeers(topPeerCategoryPeersData):
|
||||
let (_, _, topPeers) = (topPeerCategoryPeersData.category, topPeerCategoryPeersData.count, topPeerCategoryPeersData.peers)
|
||||
for topPeer in topPeers {
|
||||
switch topPeer {
|
||||
case let .topPeer(apiPeer, rating):
|
||||
case let .topPeer(topPeerData):
|
||||
let (apiPeer, rating) = (topPeerData.peer, topPeerData.rating)
|
||||
peersWithRating.append((apiPeer.peerId, rating))
|
||||
}
|
||||
}
|
||||
@@ -287,7 +291,8 @@ public func _internal_managedUpdatedRecentApps(accountPeerId: PeerId, postbox: P
|
||||
|> mapToSignal { result -> Signal<Void, NoError> in
|
||||
return postbox.transaction { transaction -> Void in
|
||||
switch result {
|
||||
case let .topPeers(_, _, users):
|
||||
case let .topPeers(topPeersData):
|
||||
let users = topPeersData.users
|
||||
let parsedPeers = AccumulatedPeers(users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
import Postbox
|
||||
import SwiftSignalKit
|
||||
|
||||
import TelegramApi
|
||||
import MtProtoKit
|
||||
|
||||
func _internal_removePeerChat(account: Account, peerId: PeerId, reportChatSpam: Bool, deleteGloballyIfPossible: Bool = false) -> Signal<Void, NoError> {
|
||||
return account.postbox.transaction { transaction -> Void in
|
||||
@@ -79,3 +80,22 @@ func _internal_removePeerChat(account: Account, transaction: Transaction, mediaB
|
||||
transaction.clearItemCacheCollection(collectionId: Namespaces.CachedItemCollection.cachedGroupCallDisplayAsPeers)
|
||||
}
|
||||
}
|
||||
|
||||
func _internal_getFutureCreatorAfterLeave(account: Account, peerId: EnginePeer.Id) -> Signal<EnginePeer?, NoError> {
|
||||
return account.postbox.transaction { transaction in
|
||||
return transaction.getPeer(peerId).flatMap(apiInputChannel)
|
||||
}
|
||||
|> mapToSignal { channel in
|
||||
guard let channel else {
|
||||
return .single(nil)
|
||||
}
|
||||
return account.network.request(Api.functions.channels.getFutureCreatorAfterLeave(channel: channel))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ in
|
||||
return .single(nil)
|
||||
}
|
||||
|> map { user in
|
||||
return user.flatMap { TelegramUser(user: $0) }.map(EnginePeer.init)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ func _internal_reportPeer(account: Account, peerId: PeerId) -> Signal<Void, NoEr
|
||||
return account.postbox.transaction { transaction -> Signal<Void, NoError> in
|
||||
if let peer = transaction.getPeer(peerId) {
|
||||
if let peer = peer as? TelegramSecretChat {
|
||||
return account.network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash)))
|
||||
return account.network.request(Api.functions.messages.reportEncryptedSpam(peer: Api.InputEncryptedChat.inputEncryptedChat(.init(chatId: Int32(peer.id.id._internalGetInt64Value()), accessHash: peer.accessHash))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.Bool?, NoError> in
|
||||
return .single(nil)
|
||||
|
||||
@@ -40,10 +40,12 @@ func _internal_requestPeerPhotos(accountPeerId: PeerId, postbox: Postbox, networ
|
||||
let totalCount:Int
|
||||
let photos: [Api.Photo]
|
||||
switch result {
|
||||
case let .photos(photosValue, _):
|
||||
case let .photos(photosData):
|
||||
let (photosValue, _) = (photosData.photos, photosData.users)
|
||||
photos = photosValue
|
||||
totalCount = photos.count
|
||||
case let .photosSlice(count, photosValue, _):
|
||||
case let .photosSlice(photosSliceData):
|
||||
let (count, photosValue, _) = (photosSliceData.count, photosSliceData.photos, photosSliceData.users)
|
||||
photos = photosValue
|
||||
totalCount = Int(count)
|
||||
}
|
||||
@@ -53,7 +55,8 @@ func _internal_requestPeerPhotos(accountPeerId: PeerId, postbox: Postbox, networ
|
||||
if let image = telegramMediaImageFromApiPhoto(photos[i]), let reference = image.reference {
|
||||
var date: Int32 = 0
|
||||
switch photos[i] {
|
||||
case let .photo(_, _, _, _, apiDate, _, _, _):
|
||||
case let .photo(photoData):
|
||||
let apiDate = photoData.date
|
||||
date = apiDate
|
||||
case .photoEmpty:
|
||||
break
|
||||
@@ -79,15 +82,18 @@ func _internal_requestPeerPhotos(accountPeerId: PeerId, postbox: Postbox, networ
|
||||
let chats: [Api.Chat]
|
||||
let users: [Api.User]
|
||||
switch result {
|
||||
case let .channelMessages(_, _, _, _, apiMessages, _, apiChats, apiUsers):
|
||||
case let .channelMessages(channelMessagesData):
|
||||
let (apiMessages, apiChats, apiUsers) = (channelMessagesData.messages, channelMessagesData.chats, channelMessagesData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messages(apiMessages, _, apiChats, apiUsers):
|
||||
case let .messages(messagesData):
|
||||
let (apiMessages, apiChats, apiUsers) = (messagesData.messages, messagesData.chats, messagesData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
case let .messagesSlice(_, _, _, _, _, apiMessages, _, apiChats, apiUsers):
|
||||
case let .messagesSlice(messagesSliceData):
|
||||
let (apiMessages, apiChats, apiUsers) = (messagesSliceData.messages, messagesSliceData.chats, messagesSliceData.users)
|
||||
messages = apiMessages
|
||||
chats = apiChats
|
||||
users = apiUsers
|
||||
|
||||
@@ -56,7 +56,8 @@ func _internal_resolvePeerByName(postbox: Postbox, network: Network, accountPeer
|
||||
var peerId: PeerId? = nil
|
||||
|
||||
switch result {
|
||||
case let .resolvedPeer(apiPeer, chats, users):
|
||||
case let .resolvedPeer(resolvedPeerData):
|
||||
let (apiPeer, chats, users) = (resolvedPeerData.peer, resolvedPeerData.chats, resolvedPeerData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
if let peer = parsedPeers.get(apiPeer.peerId) {
|
||||
@@ -105,7 +106,8 @@ func _internal_resolvePeerByPhone(account: Account, phone: String, ageLimit: Int
|
||||
var peerId: PeerId? = nil
|
||||
|
||||
switch result {
|
||||
case let .resolvedPeer(apiPeer, chats, users):
|
||||
case let .resolvedPeer(resolvedPeerData):
|
||||
let (apiPeer, chats, users) = (resolvedPeerData.peer, resolvedPeerData.chats, resolvedPeerData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
|
||||
if let peer = parsedPeers.get(apiPeer.peerId) {
|
||||
|
||||
@@ -54,7 +54,7 @@ func _internal_getSavedMusicById(postbox: Postbox, network: Network, peer: PeerR
|
||||
guard let inputUser, let resource = file.resource as? CloudDocumentMediaResource else {
|
||||
return .single(nil)
|
||||
}
|
||||
return network.request(Api.functions.users.getSavedMusicByID(id: inputUser, documents: [.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))]))
|
||||
return network.request(Api.functions.users.getSavedMusicByID(id: inputUser, documents: [.inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)))]))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.users.SavedMusic?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -62,8 +62,8 @@ func _internal_getSavedMusicById(postbox: Postbox, network: Network, peer: PeerR
|
||||
|> map { result -> TelegramMediaFile? in
|
||||
if let result {
|
||||
switch result {
|
||||
case let .savedMusic(_, documents):
|
||||
if let file = documents.first.flatMap({ telegramMediaFileFromApiDocument($0, altDocuments: nil) }) {
|
||||
case let .savedMusic(savedMusicData):
|
||||
if let file = savedMusicData.documents.first.flatMap({ telegramMediaFileFromApiDocument($0, altDocuments: nil) }) {
|
||||
return file
|
||||
}
|
||||
default:
|
||||
@@ -104,7 +104,8 @@ func _internal_keepSavedMusicIdsUpdated(postbox: Postbox, network: Network, acco
|
||||
}
|
||||
return postbox.transaction { transaction in
|
||||
switch result {
|
||||
case let .savedMusicIds(ids):
|
||||
case let .savedMusicIds(savedMusicIdsData):
|
||||
let ids = savedMusicIdsData.ids
|
||||
let savedMusicIdsList = SavedMusicIdsList(items: ids)
|
||||
transaction.setPreferencesEntry(key: PreferencesKeys.savedMusicIds(), value: PreferencesEntry(savedMusicIdsList))
|
||||
case .savedMusicIdsNotModified:
|
||||
@@ -188,9 +189,9 @@ func _internal_addSavedMusic(account: Account, file: FileMediaReference, afterFi
|
||||
var afterId: Api.InputDocument?
|
||||
if let afterFile, let resource = afterFile.media.resource as? CloudDocumentMediaResource {
|
||||
flags = 1 << 1
|
||||
afterId = .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))
|
||||
afterId = .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)))
|
||||
}
|
||||
return account.network.request(Api.functions.account.saveMusic(flags: flags, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), afterId: afterId))
|
||||
return account.network.request(Api.functions.account.saveMusic(flags: flags, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), afterId: afterId))
|
||||
})
|
||||
|> mapError { _ -> AddSavedMusicError in
|
||||
return .generic
|
||||
@@ -233,7 +234,7 @@ func _internal_removeSavedMusic(account: Account, file: FileMediaReference) -> S
|
||||
}
|
||||
let flags: Int32 = 1 << 0
|
||||
return revalidatedMusic(account: account, file: file, signal: { resource in
|
||||
return account.network.request(Api.functions.account.saveMusic(flags: flags, id: .inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference)), afterId: nil))
|
||||
return account.network.request(Api.functions.account.saveMusic(flags: flags, id: .inputDocument(.init(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: resource.fileReference))), afterId: nil))
|
||||
})
|
||||
|> `catch` { _ -> Signal<Api.Bool, NoError> in
|
||||
return .complete()
|
||||
@@ -365,10 +366,10 @@ public final class ProfileSavedMusicContext {
|
||||
return network.request(Api.functions.users.getSavedMusic(id: inputUser, offset: offset, limit: 32, hash: 0))
|
||||
|> map { result -> ([TelegramMediaFile], Int32) in
|
||||
switch result {
|
||||
case let .savedMusic(count, documents):
|
||||
return (documents.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: nil) }, count)
|
||||
case let .savedMusicNotModified(count):
|
||||
return ([], count)
|
||||
case let .savedMusic(savedMusicData):
|
||||
return (savedMusicData.documents.compactMap { telegramMediaFileFromApiDocument($0, altDocuments: nil) }, savedMusicData.count)
|
||||
case let .savedMusicNotModified(savedMusicNotModifiedData):
|
||||
return ([], savedMusicNotModifiedData.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,8 @@ public func _internal_searchPeers(accountPeerId: PeerId, postbox: Postbox, netwo
|
||||
|> mapToSignal { result -> Signal<([FoundPeer], [FoundPeer]), NoError> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .found(myResults, results, chats, users):
|
||||
case let .found(foundData):
|
||||
let (myResults, results, chats, users) = (foundData.myResults, foundData.results, foundData.chats, foundData.users)
|
||||
return postbox.transaction { transaction -> ([FoundPeer], [FoundPeer]) in
|
||||
var subscribers: [PeerId: Int32] = [:]
|
||||
|
||||
@@ -45,7 +46,8 @@ public func _internal_searchPeers(accountPeerId: PeerId, postbox: Postbox, netwo
|
||||
for chat in chats {
|
||||
if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) {
|
||||
switch chat {
|
||||
case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channel(channelData):
|
||||
let participantsCount = channelData.participantsCount
|
||||
if let participantsCount = participantsCount {
|
||||
subscribers[groupOrChannel.id] = participantsCount
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ func _internal_supportPeerId(account: Account) -> Signal<PeerId?, NoError> {
|
||||
|> mapToSignal { support -> Signal<PeerId?, NoError> in
|
||||
if let support = support {
|
||||
switch support {
|
||||
case let .support(_, user):
|
||||
case let .support(supportData):
|
||||
let user = supportData.user
|
||||
return account.postbox.transaction { transaction -> PeerId in
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: [], users: [user])
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
@@ -612,6 +612,10 @@ public extension TelegramEngine {
|
||||
}
|
||||
|> ignoreValues
|
||||
}
|
||||
|
||||
public func getFutureCreatorAfterLeave(peerId: EnginePeer.Id) -> Signal<EnginePeer?, NoError> {
|
||||
return _internal_getFutureCreatorAfterLeave(account: self.account, peerId: peerId)
|
||||
}
|
||||
|
||||
public func terminateSecretChat(peerId: PeerId, requestRemoteHistoryRemoval: Bool) -> Signal<Never, NoError> {
|
||||
return self.account.postbox.transaction { transaction -> Void in
|
||||
@@ -1648,7 +1652,7 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func getCollectibleUsernameInfo(username: String) -> Signal<TelegramCollectibleItemInfo?, NoError> {
|
||||
return self.account.network.request(Api.functions.fragment.getCollectibleInfo(collectible: .inputCollectibleUsername(username: username)))
|
||||
return self.account.network.request(Api.functions.fragment.getCollectibleInfo(collectible: .inputCollectibleUsername(.init(username: username))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.fragment.CollectibleInfo?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -1658,7 +1662,8 @@ public extension TelegramEngine {
|
||||
return nil
|
||||
}
|
||||
switch result {
|
||||
case let .collectibleInfo(purchaseDate, currency, amount, cryptoCurrency, cryptoAmount, url):
|
||||
case let .collectibleInfo(collectibleInfoData):
|
||||
let (purchaseDate, currency, amount, cryptoCurrency, cryptoAmount, url) = (collectibleInfoData.purchaseDate, collectibleInfoData.currency, collectibleInfoData.amount, collectibleInfoData.cryptoCurrency, collectibleInfoData.cryptoAmount, collectibleInfoData.url)
|
||||
return TelegramCollectibleItemInfo(
|
||||
subject: .username(username),
|
||||
purchaseDate: purchaseDate,
|
||||
@@ -1673,7 +1678,7 @@ public extension TelegramEngine {
|
||||
}
|
||||
|
||||
public func getCollectiblePhoneNumberInfo(phoneNumber: String) -> Signal<TelegramCollectibleItemInfo?, NoError> {
|
||||
return self.account.network.request(Api.functions.fragment.getCollectibleInfo(collectible: .inputCollectiblePhone(phone: phoneNumber)))
|
||||
return self.account.network.request(Api.functions.fragment.getCollectibleInfo(collectible: .inputCollectiblePhone(.init(phone: phoneNumber))))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.fragment.CollectibleInfo?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -1683,7 +1688,8 @@ public extension TelegramEngine {
|
||||
return nil
|
||||
}
|
||||
switch result {
|
||||
case let .collectibleInfo(purchaseDate, currency, amount, cryptoCurrency, cryptoAmount, url):
|
||||
case let .collectibleInfo(collectibleInfoData):
|
||||
let (purchaseDate, currency, amount, cryptoCurrency, cryptoAmount, url) = (collectibleInfoData.purchaseDate, collectibleInfoData.currency, collectibleInfoData.amount, collectibleInfoData.cryptoCurrency, collectibleInfoData.cryptoAmount, collectibleInfoData.url)
|
||||
return TelegramCollectibleItemInfo(
|
||||
subject: .phoneNumber(phoneNumber),
|
||||
purchaseDate: purchaseDate,
|
||||
@@ -1741,7 +1747,8 @@ public extension TelegramEngine {
|
||||
}
|
||||
return self.account.postbox.transaction { transaction -> TelegramResolvedMessageLink? in
|
||||
switch result {
|
||||
case let .resolvedBusinessChatLinks(_, peer, message, entities, chats, users):
|
||||
case let .resolvedBusinessChatLinks(resolvedBusinessChatLinksData):
|
||||
let (peer, message, entities, chats, users) = (resolvedBusinessChatLinksData.peer, resolvedBusinessChatLinksData.message, resolvedBusinessChatLinksData.entities, resolvedBusinessChatLinksData.chats, resolvedBusinessChatLinksData.users)
|
||||
updatePeers(transaction: transaction, accountPeerId: self.account.peerId, peers: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
|
||||
guard let peer = transaction.getPeer(peer.peerId) else {
|
||||
|
||||
@@ -90,7 +90,8 @@ func fetchAndUpdateSupplementalCachedPeerData(peerId rawPeerId: PeerId, accountP
|
||||
|
||||
let peerStatusSettings: PeerStatusSettings
|
||||
switch peerSettings {
|
||||
case let .peerSettings(settings, chats, users):
|
||||
case let .peerSettings(peerSettingsData):
|
||||
let (settings, chats, users) = (peerSettingsData.settings, peerSettingsData.chats, peerSettingsData.users)
|
||||
peerStatusSettings = PeerStatusSettings(apiSettings: settings)
|
||||
parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
}
|
||||
@@ -193,7 +194,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
|> mapToSignal { result -> Signal<EditableBotInfo?, NoError> in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .botInfo(name, about, description):
|
||||
case let .botInfo(botInfoData):
|
||||
let (name, about, description) = (botInfoData.name, botInfoData.about, botInfoData.description)
|
||||
return .single(EditableBotInfo(name: name, about: about, description: description))
|
||||
}
|
||||
} else {
|
||||
@@ -234,7 +236,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
|> mapToSignal { result, editableBotInfo, botPreview, additionalConnectedBots -> Signal<Bool, NoError> in
|
||||
return postbox.transaction { transaction -> Bool in
|
||||
switch result {
|
||||
case let .userFull(fullUser, chats, users):
|
||||
case let .userFull(userFullData):
|
||||
let (fullUser, chats, users) = (userFullData.fullUser, userFullData.chats, userFullData.users)
|
||||
var accountUser: Api.User?
|
||||
var parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
for user in users {
|
||||
@@ -248,12 +251,14 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
|
||||
if let additionalConnectedBots {
|
||||
switch additionalConnectedBots {
|
||||
case let .connectedBots(connectedBots, users):
|
||||
case let .connectedBots(connectedBotsData):
|
||||
let (connectedBots, users) = (connectedBotsData.connectedBots, connectedBotsData.users)
|
||||
parsedPeers = parsedPeers.union(with: AccumulatedPeers(transaction: transaction, chats: [], users: users))
|
||||
|
||||
if let apiBot = connectedBots.first {
|
||||
switch apiBot {
|
||||
case let .connectedBot(_, botId, recipients, rights):
|
||||
case let .connectedBot(connectedBotData):
|
||||
let (botId, recipients, rights) = (connectedBotData.botId, connectedBotData.recipients, connectedBotData.rights)
|
||||
mappedConnectedBot = TelegramAccountConnectedBot(
|
||||
id: PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(botId)),
|
||||
recipients: TelegramBusinessRecipients(apiValue: recipients),
|
||||
@@ -265,7 +270,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
}
|
||||
|
||||
switch fullUser {
|
||||
case let .userFull(_, _, _, _, _, _, _, _, userFullNotifySettings, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .userFull(userFullData):
|
||||
let userFullNotifySettings = userFullData.notifySettings
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: userFullNotifySettings)])
|
||||
}
|
||||
@@ -277,7 +283,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
previous = CachedUserData()
|
||||
}
|
||||
switch fullUser {
|
||||
case let .userFull(userFullFlags, userFullFlags2, _, userFullAbout, userFullSettings, personalPhoto, profilePhoto, fallbackPhoto, _, userFullBotInfo, userFullPinnedMsgId, userFullCommonChatsCount, _, userFullTtlPeriod, userFullChatTheme, _, groupAdminRights, channelAdminRights, userWallpaper, _, businessWorkHours, businessLocation, greetingMessage, awayMessage, businessIntro, birthday, personalChannelId, personalChannelMessage, starGiftsCount, starRefProgram, verification, sendPaidMessageStars, disallowedStarGifts, starsRating, starsMyPendingRating, starsMyPendingRatingDate, mainTab, savedMusic, note):
|
||||
case let .userFull(userFullData):
|
||||
let (userFullFlags, userFullFlags2, userFullAbout, userFullSettings, apiPersonalPhoto, profilePhoto, apiFallbackPhoto, userFullBotInfo, userFullPinnedMsgId, userFullCommonChatsCount, userFullTtlPeriod, userFullChatTheme, groupAdminRights, channelAdminRights, userWallpaper, businessWorkHours, businessLocation, greetingMessage, awayMessage, businessIntro, birthday, personalChannelId, personalChannelMessage, starGiftsCount, starRefProgram, apiVerification, apiSendPaidMessageStars, disallowedStarGifts, starsRating, starsMyPendingRating, starsMyPendingRatingDate, mainTab, savedMusic, note) = (userFullData.flags, userFullData.flags2, userFullData.about, userFullData.settings, userFullData.personalPhoto, userFullData.profilePhoto, userFullData.fallbackPhoto, userFullData.botInfo, userFullData.pinnedMsgId, userFullData.commonChatsCount, userFullData.ttlPeriod, userFullData.theme, userFullData.botGroupAdminRights, userFullData.botBroadcastAdminRights, userFullData.wallpaper, userFullData.businessWorkHours, userFullData.businessLocation, userFullData.businessGreetingMessage, userFullData.businessAwayMessage, userFullData.businessIntro, userFullData.birthday, userFullData.personalChannelId, userFullData.personalChannelMessage, userFullData.stargiftsCount, userFullData.starrefProgram, userFullData.botVerification, userFullData.sendPaidMessagesStars, userFullData.disallowedGifts, userFullData.starsRating, userFullData.starsMyPendingRating, userFullData.starsMyPendingRatingDate, userFullData.mainTab, userFullData.savedMusic, userFullData.note)
|
||||
let botInfo = userFullBotInfo.flatMap(BotInfo.init(apiBotInfo:))
|
||||
let isBlocked = (userFullFlags & (1 << 0)) != 0
|
||||
let voiceCallsAvailable = (userFullFlags & (1 << 4)) != 0
|
||||
@@ -338,9 +345,9 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
|
||||
let autoremoveTimeout: CachedPeerAutoremoveTimeout = .known(CachedPeerAutoremoveTimeout.Value(userFullTtlPeriod))
|
||||
|
||||
let personalPhoto = personalPhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let personalPhoto = apiPersonalPhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let photo = profilePhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let fallbackPhoto = fallbackPhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
let fallbackPhoto = apiFallbackPhoto.flatMap { telegramMediaImageFromApiPhoto($0) }
|
||||
|
||||
let wallpaper = userWallpaper.flatMap { TelegramWallpaper(apiWallpaper: $0) }
|
||||
|
||||
@@ -381,7 +388,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var subscriberCount: Int32?
|
||||
for chat in chats {
|
||||
if chat.peerId == channelPeerId {
|
||||
if case let .channel(_, _, _, _, _, _, _, _, _, _, _, _, participantsCount, _, _, _, _, _, _, _, _, _, _) = chat {
|
||||
if case let .channel(channelData) = chat {
|
||||
let participantsCount = channelData.participantsCount
|
||||
subscriberCount = participantsCount
|
||||
}
|
||||
}
|
||||
@@ -399,9 +407,9 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
mappedStarRefProgram = TelegramStarRefProgram(apiStarRefProgram: starRefProgram)
|
||||
}
|
||||
|
||||
let verification = verification.flatMap { PeerVerification(apiBotVerification: $0) }
|
||||
let verification = apiVerification.flatMap { PeerVerification(apiBotVerification: $0) }
|
||||
|
||||
let sendPaidMessageStars = sendPaidMessageStars.flatMap { StarsAmount(value: $0, nanos: 0) }
|
||||
let sendPaidMessageStars = apiSendPaidMessageStars.flatMap { StarsAmount(value: $0, nanos: 0) }
|
||||
|
||||
let disallowedGifts = TelegramDisallowedGifts(apiDisallowedGifts: disallowedStarGifts)
|
||||
|
||||
@@ -425,7 +433,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var mappedNote: CachedUserData.Note?
|
||||
if let note {
|
||||
switch note {
|
||||
case let .textWithEntities(text, entities):
|
||||
case let .textWithEntities(textWithEntitiesData):
|
||||
let (text, entities) = (textWithEntitiesData.text, textWithEntitiesData.entities)
|
||||
mappedNote = CachedUserData.Note(text: text, entities: messageTextEntitiesFromApiEntities(entities))
|
||||
}
|
||||
}
|
||||
@@ -486,20 +495,24 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
}
|
||||
return postbox.transaction { transaction -> Bool in
|
||||
switch result {
|
||||
case let .chatFull(fullChat, chats, users):
|
||||
case let .chatFull(messagesChatFullData):
|
||||
let (fullChat, chats, users) = (messagesChatFullData.fullChat, messagesChatFullData.chats, messagesChatFullData.users)
|
||||
switch fullChat {
|
||||
case let .chatFull(_, _, _, _, _, notifySettings, _, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .chatFull(chatFullData):
|
||||
let (notifySettings) = (chatFullData.notifySettings)
|
||||
transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)])
|
||||
case .channelFull:
|
||||
break
|
||||
}
|
||||
|
||||
switch fullChat {
|
||||
case let .chatFull(chatFullFlags, _, chatFullAbout, chatFullParticipants, chatFullChatPhoto, _, chatFullExportedInvite, chatFullBotInfo, chatFullPinnedMsgId, _, chatFullCall, chatTtlPeriod, chatFullGroupcallDefaultJoinAs, chatFullThemeEmoticon, chatFullRequestsPending, _, allowedReactions, reactionsLimit):
|
||||
case let .chatFull(chatFullData):
|
||||
let (chatFullFlags, chatFullAbout, chatFullParticipants, chatFullChatPhoto, chatFullExportedInvite, chatFullBotInfo, chatFullPinnedMsgId, chatFullCall, chatTtlPeriod, chatFullGroupcallDefaultJoinAs, chatFullThemeEmoticon, chatFullRequestsPending, allowedReactions, reactionsLimit) = (chatFullData.flags, chatFullData.about, chatFullData.participants, chatFullData.chatPhoto, chatFullData.exportedInvite, chatFullData.botInfo, chatFullData.pinnedMsgId, chatFullData.call, chatFullData.ttlPeriod, chatFullData.groupcallDefaultJoinAs, chatFullData.themeEmoticon, chatFullData.requestsPending, chatFullData.availableReactions, chatFullData.reactionsLimit)
|
||||
var botInfos: [CachedPeerBotInfo] = []
|
||||
for botInfo in chatFullBotInfo ?? [] {
|
||||
switch botInfo {
|
||||
case let .botInfo(_, userId, _, _, _, _, _, _, _, _):
|
||||
case let .botInfo(botInfoData):
|
||||
let (_, userId, _, _, _, _, _, _, _, _) = (botInfoData.flags, botInfoData.userId, botInfoData.description, botInfoData.descriptionPhoto, botInfoData.descriptionDocument, botInfoData.commands, botInfoData.menuButton, botInfoData.privacyPolicyUrl, botInfoData.appSettings, botInfoData.verifierSettings)
|
||||
if let userId = userId {
|
||||
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
let parsedBotInfo = BotInfo(apiBotInfo: botInfo)
|
||||
@@ -554,7 +567,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var updatedActiveCall: CachedChannelData.ActiveCall?
|
||||
if let inputCall = chatFullCall {
|
||||
switch inputCall {
|
||||
case let .inputGroupCall(id, accessHash):
|
||||
case let .inputGroupCall(inputGroupCallData):
|
||||
let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash)
|
||||
updatedActiveCall = CachedChannelData.ActiveCall(id: id, accessHash: accessHash, title: previous.activeCall?.title, scheduleTimestamp: previous.activeCall?.scheduleTimestamp, subscribedToScheduled: previous.activeCall?.subscribedToScheduled ?? false, isStream: previous.activeCall?.isStream)
|
||||
case .inputGroupCallSlug, .inputGroupCallInviteMessage:
|
||||
break
|
||||
@@ -566,7 +580,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
switch allowedReactions {
|
||||
case .chatReactionsAll:
|
||||
mappedAllowedReactions = .all
|
||||
case let .chatReactionsSome(reactions):
|
||||
case let .chatReactionsSome(chatReactionsSomeData):
|
||||
let reactions = chatReactionsSomeData.reactions
|
||||
mappedAllowedReactions = .limited(reactions.compactMap(MessageReaction.Reaction.init(apiReaction:)))
|
||||
case .chatReactionsNone:
|
||||
mappedAllowedReactions = .empty
|
||||
@@ -629,16 +644,19 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
return postbox.transaction { transaction -> Bool in
|
||||
if let result = result {
|
||||
switch result {
|
||||
case let .chatFull(fullChat, chats, users):
|
||||
case let .chatFull(messagesChatFullData):
|
||||
let (fullChat, chats, users) = (messagesChatFullData.fullChat, messagesChatFullData.chats, messagesChatFullData.users)
|
||||
switch fullChat {
|
||||
case let .channelFull(_, _, _, _, _, _, _, _, _, _, _, _, _, notifySettings, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .channelFull(channelFullData):
|
||||
let notifySettings = channelFullData.notifySettings
|
||||
transaction.updateCurrentPeerNotificationSettings([peerId: TelegramPeerNotificationSettings(apiSettings: notifySettings)])
|
||||
case .chatFull:
|
||||
break
|
||||
}
|
||||
|
||||
switch fullChat {
|
||||
case let .channelFull(flags, flags2, _, about, participantsCount, adminsCount, kickedCount, bannedCount, _, _, _, _, chatPhoto, _, apiExportedInvite, apiBotInfos, migratedFromChatId, migratedFromMaxId, pinnedMsgId, stickerSet, minAvailableMsgId, _, linkedChatId, location, slowmodeSeconds, slowmodeNextSendDate, statsDc, _, inputCall, ttl, pendingSuggestions, groupcallDefaultJoinAs, themeEmoticon, requestsPending, _, defaultSendAs, allowedReactions, reactionsLimit, _, wallpaper, appliedBoosts, boostsUnrestrict, emojiSet, verification, starGiftsCount, sendPaidMessageStars, mainTab):
|
||||
case let .channelFull(channelFullData):
|
||||
let (flags, flags2, about, participantsCount, adminsCount, kickedCount, bannedCount, chatPhoto, apiExportedInvite, apiBotInfos, migratedFromChatId, migratedFromMaxId, pinnedMsgId, stickerSet, minAvailableMsgId, linkedChatId, location, slowmodeSeconds, slowmodeNextSendDate, statsDc, inputCall, ttl, pendingSuggestions, groupcallDefaultJoinAs, themeEmoticon, requestsPending, defaultSendAs, allowedReactions, reactionsLimit, wallpaper, appliedBoosts, boostsUnrestrict, emojiSet, verification, starGiftsCount, sendPaidMessageStars, mainTab) = (channelFullData.flags, channelFullData.flags2, channelFullData.about, channelFullData.participantsCount, channelFullData.adminsCount, channelFullData.kickedCount, channelFullData.bannedCount, channelFullData.chatPhoto, channelFullData.exportedInvite, channelFullData.botInfo, channelFullData.migratedFromChatId, channelFullData.migratedFromMaxId, channelFullData.pinnedMsgId, channelFullData.stickerset, channelFullData.availableMinId, channelFullData.linkedChatId, channelFullData.location, channelFullData.slowmodeSeconds, channelFullData.slowmodeNextSendDate, channelFullData.statsDc, channelFullData.call, channelFullData.ttlPeriod, channelFullData.pendingSuggestions, channelFullData.groupcallDefaultJoinAs, channelFullData.themeEmoticon, channelFullData.requestsPending, channelFullData.defaultSendAs, channelFullData.availableReactions, channelFullData.reactionsLimit, channelFullData.wallpaper, channelFullData.boostsApplied, channelFullData.boostsUnrestrict, channelFullData.emojiset, channelFullData.botVerification, channelFullData.stargiftsCount, channelFullData.sendPaidMessagesStars, channelFullData.mainTab)
|
||||
var channelFlags = CachedChannelFlags()
|
||||
if (flags & (1 << 3)) != 0 {
|
||||
channelFlags.insert(.canDisplayParticipants)
|
||||
@@ -707,7 +725,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var botInfos: [CachedPeerBotInfo] = []
|
||||
for botInfo in apiBotInfos {
|
||||
switch botInfo {
|
||||
case let .botInfo(_, userId, _, _, _, _, _, _, _, _):
|
||||
case let .botInfo(botInfoData):
|
||||
let (_, userId, _, _, _, _, _, _, _, _) = (botInfoData.flags, botInfoData.userId, botInfoData.description, botInfoData.descriptionPhoto, botInfoData.descriptionDocument, botInfoData.commands, botInfoData.menuButton, botInfoData.privacyPolicyUrl, botInfoData.appSettings, botInfoData.verifierSettings)
|
||||
if let userId = userId {
|
||||
let peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(userId))
|
||||
let parsedBotInfo = BotInfo(apiBotInfo: botInfo)
|
||||
@@ -739,7 +758,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
|
||||
if let participantResult = participantResult {
|
||||
switch participantResult {
|
||||
case let .channelParticipant(_, chats, users):
|
||||
case let .channelParticipant(channelParticipantData):
|
||||
let (chats, users) = (channelParticipantData.chats, channelParticipantData.users)
|
||||
parsedPeers = parsedPeers.union(with: AccumulatedPeers(transaction: transaction, chats: chats, users: users))
|
||||
}
|
||||
}
|
||||
@@ -749,7 +769,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
let stickerPack: StickerPackCollectionInfo? = stickerSet.flatMap { apiSet -> StickerPackCollectionInfo in
|
||||
let namespace: ItemCollectionId.Namespace
|
||||
switch apiSet {
|
||||
case let .stickerSet(flags, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .stickerSet(stickerSetData):
|
||||
let flags = stickerSetData.flags
|
||||
if (flags & (1 << 3)) != 0 {
|
||||
namespace = Namespaces.ItemCollection.CloudMaskPacks
|
||||
} else if (flags & (1 << 7)) != 0 {
|
||||
@@ -758,7 +779,7 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
namespace = Namespaces.ItemCollection.CloudStickerPacks
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return StickerPackCollectionInfo(apiSet: apiSet, namespace: namespace)
|
||||
}
|
||||
|
||||
@@ -771,9 +792,11 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var invitedOn: Int32?
|
||||
if let participantResult = participantResult {
|
||||
switch participantResult {
|
||||
case let .channelParticipant(participant, _, _):
|
||||
case let .channelParticipant(channelParticipantData):
|
||||
let participant = channelParticipantData.participant
|
||||
switch participant {
|
||||
case let .channelParticipantSelf(flags, _, inviterId, invitedDate, _):
|
||||
case let .channelParticipantSelf(channelParticipantSelfData):
|
||||
let (flags, inviterId, invitedDate) = (channelParticipantSelfData.flags, channelParticipantSelfData.inviterId, channelParticipantSelfData.date)
|
||||
invitedBy = PeerId(namespace: Namespaces.Peer.CloudUser, id: PeerId.Id._internalFromInt64Value(inviterId))
|
||||
if (flags & (1 << 0)) != 0 {
|
||||
invitedOn = invitedDate
|
||||
@@ -789,7 +812,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
let emojiPack: StickerPackCollectionInfo? = emojiSet.flatMap { apiSet -> StickerPackCollectionInfo in
|
||||
let namespace: ItemCollectionId.Namespace
|
||||
switch apiSet {
|
||||
case let .stickerSet(flags, _, _, _, _, _, _, _, _, _, _, _):
|
||||
case let .stickerSet(stickerSetData):
|
||||
let flags = stickerSetData.flags
|
||||
if (flags & (1 << 3)) != 0 {
|
||||
namespace = Namespaces.ItemCollection.CloudMaskPacks
|
||||
} else if (flags & (1 << 7)) != 0 {
|
||||
@@ -798,7 +822,7 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
namespace = Namespaces.ItemCollection.CloudStickerPacks
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return StickerPackCollectionInfo(apiSet: apiSet, namespace: namespace)
|
||||
}
|
||||
|
||||
@@ -818,7 +842,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
var updatedActiveCall: CachedChannelData.ActiveCall?
|
||||
if let inputCall = inputCall {
|
||||
switch inputCall {
|
||||
case let .inputGroupCall(id, accessHash):
|
||||
case let .inputGroupCall(inputGroupCallData):
|
||||
let (id, accessHash) = (inputGroupCallData.id, inputGroupCallData.accessHash)
|
||||
updatedActiveCall = CachedChannelData.ActiveCall(id: id, accessHash: accessHash, title: previous.activeCall?.title, scheduleTimestamp: previous.activeCall?.scheduleTimestamp, subscribedToScheduled: previous.activeCall?.subscribedToScheduled ?? false, isStream: previous.activeCall?.isStream)
|
||||
case .inputGroupCallSlug, .inputGroupCallInviteMessage:
|
||||
break
|
||||
@@ -830,7 +855,8 @@ func _internal_fetchAndUpdateCachedPeerData(accountPeerId: PeerId, peerId rawPee
|
||||
switch allowedReactions {
|
||||
case .chatReactionsAll:
|
||||
mappedAllowedReactions = .all
|
||||
case let .chatReactionsSome(reactions):
|
||||
case let .chatReactionsSome(chatReactionsSomeData):
|
||||
let reactions = chatReactionsSomeData.reactions
|
||||
mappedAllowedReactions = .limited(reactions.compactMap(MessageReaction.Reaction.init(apiReaction:)))
|
||||
case .chatReactionsNone:
|
||||
mappedAllowedReactions = .empty
|
||||
@@ -943,11 +969,13 @@ func _internal_requestBotAdminPreview(network: Network, peerId: PeerId, inputUse
|
||||
return nil
|
||||
}
|
||||
switch result {
|
||||
case let .previewInfo(media, langCodes):
|
||||
case let .previewInfo(previewInfoData):
|
||||
let (media, langCodes) = (previewInfoData.media, previewInfoData.langCodes)
|
||||
return CachedUserData.BotPreview(
|
||||
items: media.compactMap { item -> CachedUserData.BotPreview.Item? in
|
||||
switch item {
|
||||
case let .botPreviewMedia(date, media):
|
||||
case let .botPreviewMedia(botPreviewMediaData):
|
||||
let (date, media) = (botPreviewMediaData.date, botPreviewMediaData.media)
|
||||
let value = textMediaAndExpirationTimerFromApiMedia(media, peerId)
|
||||
if let media = value.media {
|
||||
return CachedUserData.BotPreview.Item(media: media, timestamp: date)
|
||||
@@ -975,7 +1003,8 @@ func _internal_requestBotUserPreview(network: Network, peerId: PeerId, inputUser
|
||||
return CachedUserData.BotPreview(
|
||||
items: result.compactMap { item -> CachedUserData.BotPreview.Item? in
|
||||
switch item {
|
||||
case let .botPreviewMedia(date, media):
|
||||
case let .botPreviewMedia(botPreviewMediaData):
|
||||
let (date, media) = (botPreviewMediaData.date, botPreviewMediaData.media)
|
||||
let value = textMediaAndExpirationTimerFromApiMedia(media, peerId)
|
||||
if let media = value.media {
|
||||
return CachedUserData.BotPreview.Item(media: media, timestamp: date)
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ func _internal_updateGroupSpecificStickerset(postbox: Postbox, network: Network,
|
||||
|> mapToSignal { peer -> Signal<Void, UpdateGroupSpecificStickersetError> in
|
||||
let inputStickerset: Api.InputStickerSet
|
||||
if let info = info {
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetShortName(shortName: info.shortName)
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetShortName(.init(shortName: info.shortName))
|
||||
} else {
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetEmpty
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func _internal_updateGroupSpecificEmojiset(postbox: Postbox, network: Network, p
|
||||
|> mapToSignal { peer -> Signal<Void, UpdateGroupSpecificEmojisetError> in
|
||||
let inputStickerset: Api.InputStickerSet
|
||||
if let info = info {
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetShortName(shortName: info.shortName)
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetShortName(.init(shortName: info.shortName))
|
||||
} else {
|
||||
inputStickerset = Api.InputStickerSet.inputStickerSetEmpty
|
||||
}
|
||||
|
||||
@@ -293,7 +293,7 @@ func _internal_updatePeerEmojiStatus(account: Account, peerId: PeerId, fileId: I
|
||||
if let _ = expirationDate {
|
||||
flags |= (1 << 0)
|
||||
}
|
||||
mappedStatus = .emojiStatus(flags: flags, documentId: fileId, until: expirationDate)
|
||||
mappedStatus = .emojiStatus(.init(flags: flags, documentId: fileId, until: expirationDate))
|
||||
} else {
|
||||
mappedStatus = .emojiStatusEmpty
|
||||
}
|
||||
@@ -322,7 +322,7 @@ func _internal_updatePeerStarGiftStatus(account: Account, peerId: PeerId, starGi
|
||||
var textColor: Int32?
|
||||
for attribute in starGift.attributes {
|
||||
switch attribute {
|
||||
case let .model(_, fileValue, _):
|
||||
case let .model(_, fileValue, _, _):
|
||||
file = fileValue
|
||||
case let .pattern(_, patternFileValue, _):
|
||||
patternFile = patternFileValue
|
||||
@@ -338,7 +338,7 @@ func _internal_updatePeerStarGiftStatus(account: Account, peerId: PeerId, starGi
|
||||
let apiEmojiStatus: Api.EmojiStatus
|
||||
var emojiStatus: PeerEmojiStatus?
|
||||
if let file, let patternFile, let innerColor, let outerColor, let patternColor, let textColor {
|
||||
apiEmojiStatus = .inputEmojiStatusCollectible(flags: flags, collectibleId: starGift.id, until: expirationDate)
|
||||
apiEmojiStatus = .inputEmojiStatusCollectible(.init(flags: flags, collectibleId: starGift.id, until: expirationDate))
|
||||
emojiStatus = PeerEmojiStatus(content: .starGift(id: starGift.id, fileId: file.fileId.id, title: starGift.title, slug: starGift.slug, patternFileId: patternFile.fileId.id, innerColor: innerColor, outerColor: outerColor, patternColor: patternColor, textColor: textColor), expirationDate: expirationDate)
|
||||
} else {
|
||||
apiEmojiStatus = .emojiStatusEmpty
|
||||
|
||||
@@ -32,10 +32,10 @@ func _internal_updatePeersNearbyVisibility(account: Account, update: PeerNearbyV
|
||||
switch update {
|
||||
case let .visible(latitude, longitude):
|
||||
flags |= (1 << 0)
|
||||
geoPoint = .inputGeoPoint(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil)
|
||||
geoPoint = .inputGeoPoint(.init(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil))
|
||||
selfExpires = 10800
|
||||
case let .location(latitude, longitude):
|
||||
geoPoint = .inputGeoPoint(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil)
|
||||
geoPoint = .inputGeoPoint(.init(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil))
|
||||
case .invisible:
|
||||
flags |= (1 << 0)
|
||||
geoPoint = .inputGeoPointEmpty
|
||||
@@ -95,7 +95,7 @@ public final class PeersNearbyContext {
|
||||
public init(network: Network, stateManager: AccountStateManager, coordinate: (latitude: Double, longitude: Double)) {
|
||||
let expiryExtension: Double = 10.0
|
||||
|
||||
let poll = network.request(Api.functions.contacts.getLocated(flags: 0, geoPoint: .inputGeoPoint(flags: 0, lat: coordinate.latitude, long: coordinate.longitude, accuracyRadius: nil), selfExpires: nil))
|
||||
let poll = network.request(Api.functions.contacts.getLocated(flags: 0, geoPoint: .inputGeoPoint(.init(flags: 0, lat: coordinate.latitude, long: coordinate.longitude, accuracyRadius: nil)), selfExpires: nil))
|
||||
|> map(Optional.init)
|
||||
|> `catch` { _ -> Signal<Api.Updates?, NoError> in
|
||||
return .single(nil)
|
||||
@@ -105,14 +105,18 @@ public final class PeersNearbyContext {
|
||||
var peersNearby: [PeerNearby] = []
|
||||
if let updates = updates {
|
||||
switch updates {
|
||||
case let .updates(updates, _, _, _, _):
|
||||
case let .updates(updatesData):
|
||||
let updates = updatesData.updates
|
||||
for update in updates {
|
||||
if case let .updatePeerLocated(peers) = update {
|
||||
if case let .updatePeerLocated(updatePeerLocatedData) = update {
|
||||
let peers = updatePeerLocatedData.peers
|
||||
for peer in peers {
|
||||
switch peer {
|
||||
case let .peerLocated(peer, expires, distance):
|
||||
case let .peerLocated(peerLocatedData):
|
||||
let (peer, expires, distance) = (peerLocatedData.peer, peerLocatedData.expires, peerLocatedData.distance)
|
||||
peersNearby.append(.peer(id: peer.peerId, expires: expires, distance: distance))
|
||||
case let .peerSelfLocated(expires):
|
||||
case let .peerSelfLocated(peerSelfLocatedData):
|
||||
let expires = peerSelfLocatedData.expires
|
||||
peersNearby.append(.selfPeer(expires: expires))
|
||||
}
|
||||
}
|
||||
@@ -241,7 +245,7 @@ public func updateChannelGeoLocation(postbox: Postbox, network: Network, channel
|
||||
|
||||
let geoPoint: Api.InputGeoPoint
|
||||
if let (latitude, longitude) = coordinate, let _ = address {
|
||||
geoPoint = .inputGeoPoint(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil)
|
||||
geoPoint = .inputGeoPoint(.init(flags: 0, lat: latitude, long: longitude, accuracyRadius: nil))
|
||||
} else {
|
||||
geoPoint = .inputGeoPointEmpty
|
||||
}
|
||||
|
||||
@@ -85,35 +85,39 @@ public final class BlockedPeersContext {
|
||||
}
|
||||
return postbox.transaction { transaction -> (peers: [RenderedPeer], canLoadMore: Bool, totalCount: Int?) in
|
||||
switch result {
|
||||
case let .blocked(blocked, chats, users):
|
||||
case let .blocked(blockedData):
|
||||
let (blocked, chats, users) = (blockedData.blocked, blockedData.chats, blockedData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
var renderedPeers: [RenderedPeer] = []
|
||||
for blockedPeer in blocked {
|
||||
switch blockedPeer {
|
||||
case let .peerBlocked(peerId, _):
|
||||
case let .peerBlocked(peerBlockedData):
|
||||
let peerId = peerBlockedData.peerId
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
renderedPeers.append(RenderedPeer(peer: peer))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (renderedPeers, false, nil)
|
||||
case let .blockedSlice(count, blocked, chats, users):
|
||||
case let .blockedSlice(blockedSliceData):
|
||||
let (count, blocked, chats, users) = (blockedSliceData.count, blockedSliceData.blocked, blockedSliceData.chats, blockedSliceData.users)
|
||||
let parsedPeers = AccumulatedPeers(transaction: transaction, chats: chats, users: users)
|
||||
updatePeers(transaction: transaction, accountPeerId: accountPeerId, peers: parsedPeers)
|
||||
|
||||
var renderedPeers: [RenderedPeer] = []
|
||||
for blockedPeer in blocked {
|
||||
switch blockedPeer {
|
||||
case let .peerBlocked(peerId, _):
|
||||
case let .peerBlocked(peerBlockedData):
|
||||
let peerId = peerBlockedData.peerId
|
||||
if let peer = transaction.getPeer(peerId.peerId) {
|
||||
renderedPeers.append(RenderedPeer(peer: peer))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (renderedPeers, true, Int(count))
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user