2023-03-01 21:25:32 +04:00

88 lines
3.0 KiB
Swift

import Foundation
import Postbox
import SwiftSignalKit
import TelegramApi
import MtProtoKit
public enum CreateGroupError {
case generic
case privacy
case restricted
case tooMuchJoined
case tooMuchLocationBasedGroups
case serverProvided(String)
}
public struct CreateGroupResult {
public var peerId: EnginePeer.Id
public var failedToInvitePeerIds: [EnginePeer.Id]
public init(
peerId: EnginePeer.Id,
failedToInvitePeerIds: [EnginePeer.Id]
) {
self.peerId = peerId
self.failedToInvitePeerIds = failedToInvitePeerIds
}
}
func _internal_createGroup(account: Account, title: String, peerIds: [PeerId], ttlPeriod: Int32?) -> Signal<CreateGroupResult?, CreateGroupError> {
return account.postbox.transaction { transaction -> Signal<CreateGroupResult?, CreateGroupError> in
var inputUsers: [Api.InputUser] = []
for peerId in peerIds {
if let peer = transaction.getPeer(peerId), let inputUser = apiInputUser(peer) {
inputUsers.append(inputUser)
} else {
return .single(nil)
}
}
var flags: Int32 = 0
if let _ = ttlPeriod {
flags |= 1 << 0
}
return account.network.request(Api.functions.messages.createChat(flags: flags, users: inputUsers, title: title, ttlPeriod: ttlPeriod))
|> mapError { error -> CreateGroupError in
if error.errorDescription == "USERS_TOO_FEW" {
return .privacy
}
return .generic
}
|> mapToSignal { updates -> Signal<CreateGroupResult?, CreateGroupError> in
var failedToInvitePeerIds: [EnginePeer.Id] = []
failedToInvitePeerIds = []
switch updates {
case let .updates(updates, _, _, _, _):
for update in updates {
if case let .updateGroupInvitePrivacyForbidden(userId) = update {
failedToInvitePeerIds.append(EnginePeer.Id(namespace: Namespaces.Peer.CloudUser, id: EnginePeer.Id.Id._internalFromInt64Value(userId)))
}
}
default:
break
}
account.stateManager.addUpdates(updates)
if let message = updates.messages.first, let peerId = apiMessagePeerId(message) {
return account.postbox.multiplePeersView([peerId])
|> filter { view in
return view.peers[peerId] != nil
}
|> take(1)
|> castError(CreateGroupError.self)
|> map { _ -> CreateGroupResult in
return CreateGroupResult(
peerId: peerId,
failedToInvitePeerIds: failedToInvitePeerIds
)
}
} else {
return .single(nil)
}
}
}
|> castError(CreateGroupError.self)
|> switchToLatest
}